Many to many relation in django

Viewed 41

I have 2 models model A and model B as below

class ModelA(TimeStampedModel):
    field_a= models.TextField(default="")
    field_b= models.ManyToManyField("ModelB",
                    related_name="modeA_modelB", blank=True)

class ModelB(TimeStampedModel):
    field_c= models.TextField(default="")
    field_d= models.ManyToManyField("ModelA",
                    related_name="modeB_modelA", blank=True)

What I'm trying to achieve is whenever a model A is assigned to model B instance it should reflect in model B as well.

For example: A particular terms and conditions have several policy that will be model A, next in model B, I need to have field _d having the list of terms and condition which have that policy.

1 Answers

This is already the case, the related_name=… [Django-doc] is the name of the relation in reverse, so in this case a way to obtain the ModelA objects linked to a ModelB object. We thus can work with a single ManyToManyField:

class ModelA(TimeStampedModel):
    field_a= models.TextField(default='')
    field_b= models.ManyToManyField(
        'ModelB',
        related_name='field_d',
        blank=True
    )

class ModelB(TimeStampedModel):
    field_c = models.TextField(default='')
    # no field_d

If you now for example make a ModelA and a ModelB object, and you add the ModelB object to field_b, then in field_d of that ModelB object, it will contain the corresponding ModelA object:

my_a = ModelA.objects.create(field_a='foo')
my_b = ModelB.objects.create(field_c='foo')
my_a.field_b.add(my_b)
my_a.field_d.all()  # a queryset that contains my_b
Related