Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django related_name naming best practice in case of multiple relations

Tags:

django

After a year of Django experience I found out that I am not quite sure that I use Django related_names correctly.

Imagine I have three models

classA(models.Model):
    pass
classB(models.Model):
    pass
classC(models.Model):
    modelA = models.ForeignKey(classA)
    modelB = models.ForeignKey(classB)

Fine. Now I am thinking of adding related_name to classC's modelA and modelB, but the frustrating think is that I cannot use the same name for two fields. In other words, this code is apparently wrong

 classC(models.Model):
            modelA = models.ForeignKey(classA, related_name = 'classC') # wrong
            modelB = models.ForeignKey(classB, related_name = 'classC') # wrong

On the other hand, coming up with an approach like this:

classC(models.Model):
        modelA = models.ForeignKey(classA, related_name = 'classA') # wrong
        modelB = models.ForeignKey(classB, related_name = 'classB') # wrong

would result in a very misleading (at least for me) code. Consider this:

obj = classA.filter(classC__in = classA_qs)

So such naming results in a very disruptive code classC = classA_instance.

What is the best practice in terms of naming related_names. And is there something I am missing about ManyToManyFields ? Actually, I have a large project, but I've never used ManyToManyFields, always going for a third table like classC in the example. Is there something I am missing ?

like image 339
Edgar Navasardyan Avatar asked Nov 25 '16 18:11

Edgar Navasardyan


1 Answers

How about using variable related_names that way you can relate them according to their app and class.

class ClassB(models.Model):
    readers = ForeignKey('Reader',
            related_name='readable_%(app_label)s_%(class)s_set+')
like image 73
Gustavo Reyes Avatar answered Nov 08 '22 19:11

Gustavo Reyes