【问题标题】:Google App Engine: Creating entity categoriesGoogle App Engine:创建实体类别
【发布时间】:2013-12-09 19:07:10
【问题描述】:

我有这种实体类型Book(ndb.Model)

class Book(ndb.Model):
    title = ndb.StringProperty(required = True)

每个 Book 实体都应根据其类型“分类”在预定义的类别中(例如:“恐怖”、“奇幻”、“浪漫”等...)

我希望建立一个流派的流派链接菜单,如下所示:

<ul>
    <li><a href="/genre/horror">Horror</a></li>
    <li><a href="/genre/fantasy">Fantasy</a></li>
    <li><a href="/genre/romance">Romance</a></li>
</ul>

经过研究,我发现这可以通过不同的方式实现。一种方法是使用 choices 属性参数:

class Book(ndb.Model):
    title = ndb.StringProperty(required = True)
    genre = ndb.StringProperty(choices = ['Horror', 'Fantasy', 'Romance'])

但是,这种方法似乎没有太大的可扩展性和适应性;也就是说,如果我想包含一个新类别,我需要手动编辑 class Book(ndb.Model) 以及 流派链接菜单,以及用于创建和编辑 图书实体的表单。例如:

# new-book.html
<form method="post">

    <label>Book Title:<br><input type="text" name="title"></label>

    <label>Genres:<br>
            <input type="checkbox" name="genre" value="horror">Horror<br>
            <input type="checkbox" name="genre" value="fantasy">Fantasy<br>
            <input type="checkbox" name="genre" value="romance">Romance<br>
            # Adding New Genre */
            <input type="checkbox" name="genre" value="mystery">Mystery<br>
    </label>
    <input type="submit">
</form>

一定有更好的方法!感谢您的提示!

【问题讨论】:

    标签: python-2.7 categories app-engine-ndb


    【解决方案1】:

    您需要将属性设置为“重复”

    class Book(ndb.Model):
        title = ndb.StringProperty(required = True)
        genre = ndb.StringProperty(repeated=True)
    

    这将允许您添加和查询任意数量的类别。

    来源:https://developers.google.com/appengine/docs/python/ndb/properties?hl=de#repeated

    【讨论】:

    • @haopei 处理什么?你什么意思?它工作透明。
    • 感谢您的回答,rdodev。在这里使用此方法的一个挑战是:您将如何构建“类型菜单链接”,或者在构建复选框时查询所有类别的列表?例如,如果example.com/book/1['Mystery','Horror'],而example.com/book/2['Romance'],那么您将如何查询这两本书的所有三个类别以用于构建链接菜单?
    • 这并不完全正确。当您发出具有重复属性的相等查询时,它将匹配任何重复属性匹配的所有实体。如果要查询类型为“浪漫”和“恐怖”的书籍,可以使用 AND 查询:genre == 'Romance' AND Genre == 'Horror'。如果您想要所有与浪漫或恐怖相匹配的书籍,您可以使用genre.in(['Romance', 'Horror'])。有关重复属性查询,请参阅此页面:developers.google.com/appengine/docs/python/ndb/…
    • @PatrickCostello 对。我混淆了哪个是哪个。我以前从事的项目我们使用了很多重复的属性,所以是凭记忆进行的,但你是对的。我将交换编辑我的评论以避免混淆。
    • bks = Book.query(Book.genre == 'Romance').fetch() 将检索所有带有“浪漫”作为标签之一的书籍。我相信你也可以查询Book.query(Book.genre.in(['Romance', 'Mystery'])).fetch(),它将检索所有标记为“浪漫”或“神秘”的书籍。
    猜你喜欢
    • 1970-01-01
    • 2013-08-11
    • 1970-01-01
    • 1970-01-01
    • 2014-09-11
    • 1970-01-01
    • 2017-08-04
    • 2012-01-12
    • 2023-03-19
    相关资源
    最近更新 更多