SQLTerminal.app
now available

XPath.app
now available
Want fresh tech tips in your inbox?

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

Apps I've Built

XPath Expression Editor
Practice and improve your XPath skills with XPath Editor
Click to buy on the App Store
Photo Location Changer
Easily change the location on your photos and videos
Click here for more info about the app
Photo Date Changer
Easily change the dates and times on your photos and videos
Click here for more info about the app
VocabReminder
English dictionary with notifications so you won't forget what you're studying!
Click here for more info about the app
VocabQuiz
The app that quizzes and scores you on your vocabulary!
Click here for more info about the app