ReferenceProperty filter
I have a List kind, and an User kind. I'm currently using IntegerProperty to associate User IDs with Lists, but I want to switch to ReferenceProperty. Currently, I'm using this code (with IntegerProperty):
db.GqlQuery("SELECT * FROM List WH开发者_如何学CERE UserID = :1", userid)
How should the code with ReferenceProperty look like? The script has the numeric ID of User (userid).
First, you need to construct a key from your ID. You can do that like this (presuming your User entity has no parent):
user_key = db.Key.from_path('UserInfo', user_id)
Now you can use it in a query just as you would anything else:
db.GqlQuery("SELECT * FROM List WHERE user_key = :1", user_key)
Or equivalently with a Query instead of GQL:
List.all().filter("user_key =", user_key)
With a ReferenceProperty you'll need an actual entity for it to reference. So the code would essentially be the same, except userid would not be an int, it would be an entity (or I think a key to an entity would work in this case). If you're trying to switch to ReferenceProperty I'm assuming you want to start using a User entity in your List instead of user id, so it would look something like...
user = User.all()[0] # or some other thing to get your user
db.GqlQuery("SELECT * FROM List WHERE user = :1", user)
精彩评论