Monday, November 28, 2016

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

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.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/f109494e-ea45-4eb4-b6af-3fc80376b81f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment