Search code examples
djangodjango-modelsmany-to-manymanytomanyfieldjunction-table

How to add an entry to ManyToManyField in Django?


I have the following models:

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')

If I wasn't using the through keyword, I could have just added an element to votes field in Comment object (having uuid of id), like this: Comment.objects.get(uuid=id).votes.add(some_user) But this won't work here, since I have to store a vote_type for each entry in comments_votes table. How can this be done?


Solution

  • Just create the Vote instance as described in the docs:

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