[magic-removal] Reverse foreign-key lookups should take related_name into account
|Reported by:||andreas@…||Owned by:||russellm|
|Has patch:||no||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
Currently reverse ForeignKey lookups are impossible for models which are related to other models more than once. Could this be fixed by using the related_name instead of the model's name for resolving the one-to-many lookup?
class Poll(models.Model): question = models.CharField(maxlength=200) class Choice(models.Model): name = models.CharField(maxlength=100) poll = models.ForeignKey(Poll, related_name="choice") related_poll = models.ForeignKey(Poll, related_name="related_choice")
first_poll = Poll(question = "What's the first question?") first_poll.save() second_poll = Poll(question = "What's the second question?") second_poll.save() new_choice = Choice( poll = first_poll, related_poll = second_poll, name = "This is the answer." ) new_choice.save() # The current state: try: Poll.objects.get_object(choice__name__exact="This is the answer.") except TypeError: # raises TypeError with "Cannot resolve keyword 'choice' into field" # because more than one field could be identified by "choice" pass # How it could be (lookups by related_name): Poll.objects.get_object(choice__name__exact="This is the answer.") # returns first poll Poll.objects.get_object(related_choice__name__exact="This is the answer.") # returns second poll
On a related note: It seems inconsistent to me that two ForeignKeys related to the same model result in a reverse lookup exception but, e.g., a ForeignKey and a ManyToMany-Field related to the same model don't raise the "TypeError: Can't resolve keyword" exception (the ManyToManyField is used, the ForeignKey ignored).