English dictionary with notifications so you won't forget what you're studying!
Click here for more info about the app
The app that quizzes and scores you on your vocabulary!
Click here for more info about the app

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

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 w/ #manytomany through #m2m #django #orm #database #sql #python