Get or Create matching Key and User (Python - App

2019-08-06 00:28发布

Trying to match a record and user using 'get_or_insert' in Python on Google App Engine.

Using the below Models, I want to check if a User has a record for a Book already created (listed in BookUser), if they do have a record in BookUser get the details for it. If they don't create it with XX data and associate it to the Book and User.

class User(db.Model):
   id = db.StringProperty()
   name = db.StringProperty()
   image = db.BlobProperty(default=None)

class Book(db.Model):
   image = db.BlobProperty()
   date_added = db.DateTimeProperty(auto_now_add=True)
   is_active = db.BooleanProperty(default=True)

class BookUser(db.Model):
   book = db.ReferenceProperty(Book)
   user = db.ReferenceProperty(User)
   is_active = db.BooleanProperty(default=True)

I'm still wrapping my head around App Engine, keys and such. Any help would be great, appreciate it.

d

1条回答
家丑人穷心不美
2楼-- · 2019-08-06 01:10

You could make the BookUser entity's key a composite of the User and Book's key, that will give you a very simple way of making the relationship unique.

bookuser_key_name = "%s:%s" % (str(book_key.id_or_name()), str(user_key.id_or_name()))
bookuser = BookUser.get_or_insert(bookuser_key_name)
# set your values...
bookuser.put()
查看更多
登录 后发表回答