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_name
s. 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 ?
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+')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With