Simplified example of what I wrote today:
class Grandparent(models.Model):
text = models.CharField(max_length=5, choices=too_many)
class Parent(models.Model):
grandparent = models.ForeignKey(Grandparent, on_delete=models.CASCADE)
info = models.CharField(max_length=30)
class ChildSomething(models.Model):
parent = models.ForeignKey(Parent, on_delete=models.CASCADE)
data = models.CharField(max_length=5, choices=chromosome_identities)
Given a specific Grandparent object, I wanted to order Parent objects underneath it by most ChildSomething's each Parent has, which I did successfully below.
grandparent = Grandparent.objects.get(id=32923) # arbitrary id
# This query produces the desired result
parents = (
Parent.objects.filter(grandparent=grandparent).
annotate(num_child_somethings = Count('childsomething')).
order_by('num_child_somethings')
)
My question: Why is it Count('childsomething') instead of Count('child_something')? The latter was my intuition, which was corrected by a helpful Django error message:
Exception Type: FieldError
Exception Value:
Cannot resolve keyword 'user_translation' into field. Choices are: id, translate_text, translate_text_id, translation, usertranslation
The answer to this is likely simple, I just couldn't find anything in the docs related to this. How does the naming convention work? If anyone knows of the appropriate Django docs link that would be ideal. Thank you.
CodePudding user response:
Why is it
Count('childsomething')
instead ofCount('child_something')
?
Django makes use of the related_query_name=…
parameter [Django-doc] to specify a relation in reverse. If you thus specify related_query_name='child_something'
in the ForeignKey
of ChildSomething
named parent
, then this would have worked.
If you do not fill in a value for the related_query_name=…
parameter, then Django will look for the related_name=…
parameter [Django-doc] which is also used to access relations in reverse.
If both are not filled in, Django will automatically construct a value for the related_query_name=…
parameter, which is the name of the class where the ForeignKey
is defined in lowercase, so for ChildSomething
, that is simply childsomething
.
If you thus want to specify this with child_something
, you should override the related_query_name=…
parameter or the related_name=…
parameter when you construct the ForeignKey
.