如何在Django中向ManyToManyField添加一个条目?

时间:2015-05-13 14:19:11

标签: django django-models many-to-many manytomanyfield junction-table

我有以下型号:

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。怎么办呢?

1 个答案:

答案 0 :(得分:2)

只需将Vote实例创建为described in the docs

Vote.objects.create(cmt=Comment.objects.get(uuid=id),
                    user=some_user, vote_type=1)