How to avoid duplicates in GAE datastore?
假设这里是数据库结构:
1 2 3 4 5 6 7 | class News(db.Model): title = db.StringProperty() class NewsRating(db.Model): user = db.IntegerProperty() rating = db.IntegerProperty() news = db.ReferenceProperty(News) |
每个用户只能为每个新闻留下一个评分。以下代码不关心重复:
1 2 3 4 5 | rating = NewsRating() rating.user = 123456 rating.rating = 1 rating.news = News.get_by_key_name('news-unique-key') rating.put() |
我应该如何修改它允许每个
使用键名和(可能)父实体来跟踪。例如,假设你有一个
1 2 3 4 5 6 7 | 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() |
尝试多次添加相同的评分只会覆盖现有评分,或者您可以使用数据存储事务以原子方式添加它。
请注意,您几乎肯定应该针对