PaleNeutron
PaleNeutron

Reputation: 3215

How to change django base class's related_name?

I am stuck in this condition:

I have two different relation point to the same model, so I have to give the m2m field a related_name.

class A(models.Model):
    b = models.ForeignKey(B, on_delete=models.SET_NULL, null=True,)
    b_m2m = models.ManyToManyField(B, verbose_name='additional_a',
                                              blank=True, related_name="additional_a_group")

It works well until I want to inherit it

class ABase(models.Model):
    b = models.ForeignKey(B, on_delete=models.SET_NULL, null=True,)
    b_m2m = models.ManyToManyField(B, verbose_name='additional_a',
                                              blank=True, related_name="additional_a_group")
    class Meta:
        abstract = True

class A(ABase):
    pass

class C(ABase):
    pass

Now the problem is, B's reverse relation to both A and C have the same related_name additional_a_group and I do not know how to resolve it.

If I remove the related_name in ABase, b and b_m2m will conflict. However, if I leave it here, A and C will conflict.

I looked back into source code, related_name is used by ManyToManyRel.get_accessor_name. Maybe I could resolve it by overwrite both ManyToManyField and ManyToManyRel, but is there something easier?

Upvotes: 0

Views: 63

Answers (1)

Blackdoor
Blackdoor

Reputation: 982

it needs to generate two different related_names.

b_m2m = models.ManyToManyField(
    B, 
    verbose_name='additional_a',
    blank=True, 
    related_name="%(class)s_additional_a_group"
)

Upvotes: 1

Related Questions