如何避免 GAE 数据存储中出现重复?
假设数据库结构如下:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用键名称和(可能)父实体来跟踪。例如,假设您有一个
UserInfo
类型,您可以这样做:多次尝试添加相同的评级只会覆盖现有的评级,或者您可以使用数据存储事务以原子方式添加它。
请注意,您几乎肯定应该保留针对
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: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.