related_name for two models which have same name but belong to different app

43 views
Skip to first unread message

Xueguang Yang

unread,
Nov 28, 2016, 9:55:45 PM11/28/16
to Django users
Hi:

I am a little confused about this section of django official docs: Be careful with related_name

when you are using related_name in an abstract base class (only), part of the name should contain '%(app_label)s' and '%(class)s'.

However, if related_name only containe '%(class)' is still OK if there isn't two models which have the same name. In this case, if I define a new model that it's name conflict to a existing model, it can not pass the inspection when run makemigrations command. I'll show you a simple example similar to example in official docs.

common/models.py

from
django.db import models

class Base(models.Model):
   
m2m = models.ManyToManyField(OtherModel, related_name="%(class)s_related")

   
class Meta:
       
abstract = True

app1/models.py

from django,db import models
from common,models import Base

class Child(Base):
   
pass

app2/models.py

from django,db import models
from common,models import Base

class Child(Base):
   
pass

This would raise an exception when run makemigrations command because two child model in different apps have the same related_name: child_related.

However, if I delete app2, migrate process would be OK. Then I create app2 add the those codes again, Exception would raised. Though I explicitly assign a default_related_name in Meta option for Child model in app2, it can't solve the problem.

It seems we have to change the source code in Base model such as add a '%(app_label)' part for related_name, but everything in app1 need change too.

So why doesn't django force developer to add %(class) and %(app_label) even there are no conflicts for all models. Because if don't,  though there is no conflict now, it still has a potential conflict in the future.

Reply all
Reply to author
Forward
0 new messages