在实体创建期间将作者分配给实体 [英] Assigning an author to an entity during its creation

查看:29
本文介绍了在实体创建期间将作者分配给实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Google Appengine 和 Python 学习 Udacity 的网络开发课程.

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.

例如,我有两个 ndb.Models 类型:

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)

当一个Blog 实体是由一个登录用户创建的,它自己的作者(User 实体)也应该用它来标识.

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

最终,我想显示带有作者信息的博客帖子(例如,作者的bio)

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

如何实现?

推荐答案

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

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)

为了优化,如果您知道登录用户的 ndb.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)

全文:

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 的开头标准化为实用函数,您可能会获得奖励积分.

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

这篇关于在实体创建期间将作者分配给实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆