[Django]-How to avoid django "clashes with related m2m field" error?

10👍

I found a solution in Django documention.

It’s possible to write in abstract models things like this:related_name="%(app_label)s_%(class)s_related"

2👍

Normally if you add a related_name as suggested in your M2M definition, it should work :

class Voteable(models.Model):
    likes_balance = models.IntegerField(default=0, editable=False)
    votes = models.ManyToManyField(User, blank=True, editable=False, related_name='votes')
    likes = models.ManyToManyField(User, blank=True, editable=False, related_name='likes')

    class Meta:
        abstract = True

It’s because by not doing so, Django will add two user_id in the Voteable table, resulting in a clash because there is twice the same column name. Adding a related_name force Django to use the given related_name instead of the {Foreign Table Name}_id column name.

Hope this helps.

Leave a comment