【问题标题】:Assigning an author to an entity during its creation在创建实体期间将作者分配给实体
【发布时间】:2013-11-15 16:21:06
【问题描述】:

我正在使用 Google Appengine 和 Python 学习 Udacity 的 Web 开发课程。

我想知道如何分配给创建的实体,它自己的作者

例如,我有两种 ndb.Models:

class User(ndb.Model):
    username = ndb.StringProperty(required = True)
    bio = ndb.TextProperty(required = True)
    password = ndb.StringProperty(required = True)
    email = ndb.StringProperty()
    created = ndb.DateTimeProperty(auto_now_add = True)

class Blog(ndb.Model):
    title = ndb.StringProperty(required = True)
    body = ndb.TextProperty(required = True)
    created = ndb.DateTimeProperty(auto_now_add = True)

Blog 实体由登录用户创建时,它自己的作者(User 实体)也应该用它来标识。

最后,我想显示博客文章及其作者信息(例如,作者的简历

如何做到这一点?

【问题讨论】:

    标签: python google-app-engine google-cloud-datastore app-engine-ndb


    【解决方案1】:

    您的Blog 类应该包含一个属性来存储编写它的用户的密钥:

    author = ndb.KeyProperty(required = True)
    

    然后您可以在创建博客实例时设置此属性:

    blog = Blog(title="title", body="body", author=user.key)
    

    为了优化,如果您知道登录用户的 ndb.Key,并且您不需要用户实体本身,您将直接传递它,而不需要先获取用户。

    assert isinstance(user_key, ndb.Key)
    blog = Blog(title="title", body="body", author=user_key)
    

    全文:

    class User(ndb.Model):
        username = ndb.StringProperty(required = True)
        password = ndb.StringProperty(required = True)
        email = ndb.StringProperty()
        created = ndb.DateTimeProperty(auto_now_add = True)
    
    class Blog(ndb.Model):
        title = ndb.StringProperty(required = True)
        body = ndb.TextProperty(required = True)
        created = ndb.DateTimeProperty(auto_now_add = True)
        author = ndb.KeyProperty(required = True)
    
    def new_blog(author):
        """Creates a new blog post for the given author, which may be a ndb.Key or User instance"""
        if isinstance(author, User):
            author_key = author.key
        elif isinstance(author, ndb.Key):
            assert author.kind() == User._get_kind()  # verifies the provided ndb.Key is the correct kind.
            author_key = author
    
        blog = Blog(title="title", body="body", author=author_key)
        return blog
    

    如果您将 new_blog 的开头标准化为实用函数,您可能会获得奖励分

    【讨论】:

    • 谢谢@Josh。我想我明白了!后续问题:将作者存储为 KeyProperty 是否是最佳方式?在这种情况下,使用 KeyPropertyStringProperty 有什么优势?
    • 如果您希望作者的姓名能够更改,您需要使用KeyProperty。您可以使用author = blog.author.get() 获取作者,然后使用author.username 获取用户名 - 如果您想压缩为一行,则使用blog.author.get().username,但最好保留作者参考。
    • 我刚刚遇到ReferenceProperty 属性,它似乎与此处描述的解决方案非常相似。在这种情况下,是否有任何理由使用 KeyProperty 而不是 ReferenceProperty?
    • ReferenceProperty 特定于 db(不是 ndb,这是您正在使用的)。 ReferenceProperty 或多或少已被弃用,根据我的经验,从长远来看,避免它们更容易(用于优化)。最好准确了解您的代码何时从数据存储中提取,并且 ReferenceProperty 混淆了该功能。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-17
    • 1970-01-01
    • 2018-01-25
    • 1970-01-01
    相关资源
    最近更新 更多