Written by Sean Behan on Fri Jul 21st 2017

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)

Tagged with..
#manytomany through #m2m #django #orm #database #sql #python

Just finishing up brewing up some fresh ground comments...