我有以下型号:
class Vote(models.Model):
cmt = models.ForeignKey(Comment)
user = models.ForeignKey(User)
vote_type = models.SmallIntegerField(default=0) # vote_type is +1 for upvote & -1 for downvote
class Comment(models.Model):
uuid = models.CharField(max_length=40, default='random')
user = models.OneToOneField(User, primary_key=True) # ForeignKey('User')
text = models.CharField(max_length=300, null=True)
votes = models.ManyToManyField(User, through='Vote', related_name='votes_table')
如果我没有使用through
关键字,我可以在Comment对象中添加一个元素到投票字段(具有id
的uuid),如下所示:Comment.objects.get(uuid=id).votes.add(some_user)
但这不适用于此,因为我必须为vote_type
表中的每个条目存储comments_votes
。怎么办呢?
答案 0 :(得分:2)
只需将Vote
实例创建为described in the docs:
Vote.objects.create(cmt=Comment.objects.get(uuid=id),
user=some_user, vote_type=1)