我的模型如下:
class Vote(models.Model):
vote_type = models.BooleanField()
voted_by = models.ForeignKey(User, related_name='voted_by')
voted_for = models.OneToOneField(User, related_name='voted_for')
article = models.ForeignKey(Article, null=True, blank=True)
dtobject = models.DateTimeField(auto_now_add=True)
我想确保用户只能投票一次对象。 因此,在我看来,我做了以下几点:
v = Vote.objects.get_or_create(
vote_type = vtype.get(field_name),
voted_by_id = request.user.id,
voted_for_id = mobj.shared_by_id,
shared_object_id = oid
)
它第一次正常工作,但是当已经存在投票时,我得到完整性错误,原因很明显。鉴于上述模型和观点,确保对象未被投票的好方法是什么?
答案 0 :(得分:1)
get_or_create中的参数分为两部分:第一部分是唯一必须存在的实例的完全匹配,其他变量数据必须在名为“defaults”的参数中找到
请参阅文档https://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create:
obj, created = Person.objects.get_or_create(first_name='John',
last_name='Lennon', defaults={'birthday': date(1940, 10, 9)})
不确定这里的唯一关键是什么,我只是猜测它是voted_by和voted_for,所以我们有:
vote, created = Vote.objects.get_or_create(
voted_by = request.user,
vote_type = vtype.get(field_name),
defaults = dict(
voted_for_id = mobj.shared_by_id,
shared_object_id = oid
)
)
答案 1 :(得分:0)
get_or_create
返回一个元组。
vote, created = Vote.objects.get_or_create(
vote_type = vtype.get(field_name),
voted_by = request.user,
voted_for_id = mobj.shared_by_id,
shared_object_id = oid
)
其中created
为True
或False
,表示是否从数据库创建或检索。