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

How to add an entry to ManyToManyField in Django?

我有以下型号:

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 对象的 votes 字段中添加一个元素(具有 id 的 uuid),如下所示:Comment.objects.get(uuid=id).votes.add(some_user) 但这在这里行不通,因为我必须为 comments_votes table 中的每个条目存储一个 vote_type。如何做到这一点?

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

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