Assigning an author to an entity during its creation

烈酒焚心 提交于 2019-12-11 13:34:38

问题


I am doing Udacity's Web Dev Course with Google Appengine and Python.

I would like to know how I could assign to a created entity, its own author.

For example, I have two ndb.Models kinds:

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)

When a Blog entity is created by a logged-in user, its own author (User entity) should also be identified with it.

Ultimately, I would like to display a blog's post with its author's information (for example, the author's bio)

How can this be achieved?


回答1:


Your Blog class should include a property to store the key of the user who wrote it:

author = ndb.KeyProperty(required = True)

You can then set this property when you create a Blog instance:

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

For optimization, if you know the logged in user's ndb.Key, and you don't need the user entity itself, you would pass that directly, instead of needing to fetch the user first.

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

In full:

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

You may get bonus points if you standardize the beginning of new_blog to a utility function.



来源:https://stackoverflow.com/questions/20005657/assigning-an-author-to-an-entity-during-its-creation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!