Passing object in find()

22 views
Skip to first unread message

hugoleve...@gmail.com

unread,
Feb 22, 2014, 10:26:42 AM2/22/14
to mogo-...@googlegroups.com
Hi

I would like to know how to pass an object reference in a query

ex:

city = City.find_one({ "name" : "new-york" })
user = User.find({"name" : "John" , "city" : city })

Is it suposed to work this way? If not, what is the best way to pass an object in a query?


Josh Marshall

unread,
Feb 22, 2014, 1:53:22 PM2/22/14
to mogo-...@googlegroups.com
Hi Hugo --

`find()` and `find_one()` are direct passthroughs to PyMongo, i.e. we
don't make any changes to the query. You want to use `search()` or
`first()`, which takes keyword parameters:

city = City.first(name="new-york")
users = User.search(city=city)

Keep in mind, this only works if the User model has a `city` attribute
that is a ReferenceField.
Let me know if you have any questions!
---
Josh Marshall
(254) 498-0366
> --
> You received this message because you are subscribed to the Google Groups
> "Mogo Python Object Wrapper" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to mogo-python...@googlegroups.com.
> For more options, visit https://groups.google.com/groups/opt_out.

hugoleve...@gmail.com

unread,
Feb 22, 2014, 2:31:20 PM2/22/14
to mogo-...@googlegroups.com
Ha perfect!

But this gives me another question. Can I aslso do comparative in the query? .search() seems to only accept kwargs

ex:
city = City.first()
users = User.search({"age": {"$gte" : 18}} , city = city  )

Josh Marshall

unread,
Feb 22, 2014, 5:58:07 PM2/22/14
to mogo-...@googlegroups.com
Nope, unfortunately that's the limitation of the `search` and `first`
shortcuts. It would be fairly error-prone for us to try and dig into
nested queries and try to find all the objects to convert, etc.

However, if you need to do both, you can always call .get_ref() on a
model and pass that into find:

User.find({"city": city.get_ref(), "age": {"$gte": 18}})
---
Josh Marshall
(254) 498-0366


hugoleve...@gmail.com

unread,
Feb 22, 2014, 6:05:59 PM2/22/14
to mogo-...@googlegroups.com
Quite simple workaround :)

Will try that. Thanks alot for this module. Very handy
Reply all
Reply to author
Forward
0 new messages