djangodjango-modelsmanytomanyfield

How to add custom field in manytomany through table in Django


I have a model which has manytomany relation with another model. This creates a hidden through table with two foreign key field of previous two tables. Now I want to add custom field in addition to the existing two foreign key field in the through table.

Model One:

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

Model Two:

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

Auto created hidden through table:

class appname_modeltwo_modelone(models.Model):
    model_one_id= models.ForeignKey(ModelOne)
    model_two_id= models.ForeignKey(ModelTwo)
    custom_field= models.CharField(max_length=264) # New Custom Field I want to add

How can I add new custom field here?


Solution

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