如何在python-google-appengine数据库中实现一对一关系?

2024-04-19 14:24:31 发布

您现在位置:Python中文网/ 问答频道 /正文

class User(db.Model):
    username = db.StringProperty(required=True)
    password = db.StringProperty(required=True)
    email_address = db.StringProperty(required=True)
    profile_img = db.BlobProperty()

class Book(db.Model):
    user = db.ReferenceProperty(User, collection_name='books')
    #first build
    Book_1 = db.BooleanProperty(default=False) 
    Book_2 = db.BooleanProperty(default=False) 
    Book_3 = db.BooleanProperty(default=False) 
    Book_4 = db.BooleanProperty(default=False)

嗨,我想和这两种模式建立一对一的关系。我能做些什么使它永远不会为每个用户创建一个以上的图书模型?你知道吗

谢谢。你知道吗


Tags: falsetruedefaultdbmodeladdressemailrequired
1条回答
网友
1楼 · 发布于 2024-04-19 14:24:31

我认为get or insert可能对这个有用。也许当你创建你的用户模型时,你可以get_or_insert以用户名(可能是唯一的)作为键的图书模型,显然第一次创建它,然后得到它。你知道吗

Model.get_or_insert (key_name, **kwds)

Attempts to get the entity of the model's kind with the given key name. If it exists, get_or_insert() simply returns it. If it doesn't exist, a new entity with the given kind, name, and parameters in kwds is created, stored, and returned.

The get and subsequent (possible) put operations are wrapped in a transaction to ensure atomicity. Ths means that get_or_insert() will never overwrite an existing entity, and will insert a new entity if and only if no entity with the given kind and name exists.

相关问题 更多 >