I am trying to understand the 1-to-many relationships in datastore; but I fail to understand how query and update the record of a user when the model includes ReferenceProperty
. Say I have this model:
class User(db.Model):
userEmail = db.StringProperty()
userScore = db.IntegerProperty(default=0)
class Comment(db.Model):
user = db.ReferenceProperty(User, collection_name="comments")
comment = db.StringProperty()
class Venue(db.Model):
user = db.ReferenceProperty(User, collection_name="venues")
venue = db.StringProperty()
If I understand correctly, the same user, uniquely identified by userEmail
can have many comments and may be associated with many venues (restaurants etc.)
Now, let's say the user az@example.com
is already in the database and he submits a new entry.
Based on this answer I do something like:
q = User.all()
q.filter("userEmail =", az@example.com)
results = q.fetch(1)
newEntry = results[0]
But I am not clear what this does! What I want to do is to update comment
and venue
fields which are under class Comment
and class Venue
.
Can you help me understand how this works? Thanks.
The snippet you posted is doing this (see comments):
After this code
the_user
will be an object that corresponds to the user record with email"az@example.com"
. Seing you've set up your reference properties, you can access its comments and venues withthe_user.comments
andthe_user.venues
. Some venue of these can be modified, say like this:I suggest that you make a general sweep of the gae documentation that has very good examples, you will find it very helpful: http://code.google.com/appengine/docs/python/overview.html
** UPDATE **: For adding new venue to user, simply create new venue and assign the queried user object as the venue's user attribute:
To get all Comments for a given user, filter the user property using the key of the user:
So you could first lookup the user by the email, and then search comments or venues using its key.