[Django]-How to add custom field in manytomany through table in Django

10👍

You can add extra fields on many-to-many relationships using the through argument to point to the model that will act as an intermediary according to django doc

In your example

class ModelOne(models.Model):
    field_one = models.CharField(max_length=264)

class ModelTwo(models.Model):
    many_field = models.ManyToManyField(ModelOne, related_name='some_name', through='IntermediateModel')
    field_one = models.CharField(max_length=264)

class IntermediateModel(models.Model):
    model_one = models.ForeignKey(ModelOne, on_delete=models.CASCADE)
    model_two = models.ForeignKey(ModelTwo, on_delete=models.CASCADE)
    custom_field = models.DateField()
    custom_field_2 = models.CharField(max_length=64)

Leave a comment