About Defining Many-to-many Through Model
When you need extra fields for a many-to-many relationship, you use the through model. In the through_fields attribute of many-to-many relation, the first field of should point to this model, and the second one should point to the other related model. For example,
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=200)
authors = models.CharField(max_length=200)
def __str__(self):
return self.title
class Reader(models.Model):
name = models.CharField(max_length=200)
reading_list = models.ManyToManyField(
Book, through="BookToRead", through_fields=("reader", "book")
)
def __str__(self):
return self.name
class BookToRead(models.Model):
book = models.ForeignKey(Book, on_delete=models.CASCADE)
reader = models.ForeignKey(Reader, on_delete=models.CASCADE)
priority = models.PositiveIntegerField()
added_date = models.DateTimeField()
def __str__(self):
return f"{self.reader} wants to read {self.book}"
Django/Python Consulting
If you have a specific Django challenge or integration you'd like to solve, I'd be happy to help. Book a free 30-minute call to discuss your project, see if we're a good fit, and explore the best approach for your needs. After the call, you'll receive a tailored cost estimate based on what we discuss.
Also by me
Django Messaging
For Django-based social platforms.
Django Paddle Subscriptions
For Django-based SaaS projects.
Django GDPR Cookie Consent
For Django websites that use cookies.