如何避免 GAE 数据存储中出现重复?

发布于 2024-12-10 05:00:05 字数 557 浏览 2 评论 0原文

假设数据库结构如下:

class News(db.Model):
    title = db.StringProperty()

class NewsRating(db.Model):
    user = db.IntegerProperty()
    rating = db.IntegerProperty()
    news = db.ReferenceProperty(News)

每个用户只能对每个新闻留下一个评分。以下代码不关心重复项:

rating = NewsRating()
rating.user = 123456
rating.rating = 1
rating.news = News.get_by_key_name('news-unique-key')
rating.put()

我应该如何修改它,使其只允许每个 rating.user 和 rating.news 组合有一条记录?如果此类评级已存在,则应使用新值进行更新。

Let's say here is the database structure:

class News(db.Model):
    title = db.StringProperty()

class NewsRating(db.Model):
    user = db.IntegerProperty()
    rating = db.IntegerProperty()
    news = db.ReferenceProperty(News)

Each user can leave only one rating for each News. The following code doesn't care about duplicates:

rating = NewsRating()
rating.user = 123456
rating.rating = 1
rating.news = News.get_by_key_name('news-unique-key')
rating.put()

How should I modify that that it will allow to have only one record for each rating.user and rating.news combination? If such rating already exists, then it should be updated with new value.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

哎呦我呸! 2024-12-17 05:00:05

使用键名称和(可能)父实体来跟踪。例如,假设您有一个 UserInfo 类型,您可以这样做:

class NewsRating(db.Model):
  # No explicit user reference, since it's the parent entity
  rating = db.IntegerProperty(required=True)
  news = db.ReferenceProperty(News) # We could get this from the key name, but this is more convenient

rating = NewsRating(parent=current_user, key_name=str(news.key().id()), news=news)
rating.put()

多次尝试添加相同的评级只会覆盖现有的评级,或者您可以使用数据存储事务以原子方式添加它。

请注意,您几乎肯定应该保留针对 News 实体的评分总数,而不是计算每个请求的评分,随着评分数量的增加,效率会降低。

Use key names and (possibly) parent entities to keep track. For instance, supposing you have a UserInfo kind, you could do it like this:

class NewsRating(db.Model):
  # No explicit user reference, since it's the parent entity
  rating = db.IntegerProperty(required=True)
  news = db.ReferenceProperty(News) # We could get this from the key name, but this is more convenient

rating = NewsRating(parent=current_user, key_name=str(news.key().id()), news=news)
rating.put()

Attempting to add the same rating multiple times will simply overwrite the existing one, or you can use a datastore transaction to add it atomically.

Note that you should almost certainly keep a total of ratings against the News entity, rather than counting up ratings on each request, which will get less efficient as the number of ratings increases.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文