· 1 min read

Manual ManyToMany Through with Django's ORM

Here is a code snippet that demonstrates how to set up a ManyToMany through relationship in Django. In Rails, the equivalent would be called a has_many through association.

If you set the through argument on the ManyToManyField, Django will not automatically manage the intermediate join table for you and it will be your responsibility to manage the table. This is common when you want to add extra columns on the intermediate table.

class Post(models.Model):
    pass

class Category(models.Model):
    posts = models.ManyToManyField(Post, through='PostCategory', related_name='categories')

class PostCategory(models.Model):
    post = models.ForeignKey(Post)
    category = models.ForeignKey(category)

Comments

Leave a comment