Opened 3 years ago

Closed 3 years ago

#17661 closed Bug (invalid)

Foreign key with related name is not working properly.

Reported by: davisito89@… Owned by: nobody
Component: Database layer (models, ORM) Version: 1.3
Severity: Normal Keywords: related_name
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

I created a class Person and a class Email. The relationship is 1:n (a person can have many emails and an email belongs to only one person). My class Email contains an attribute named person = models.ForeignKey(u"Person", related_name = u"emails"). Then I get some errors trying to get the emails of a single person:

  1. I created a person.

Person.objects.create(id = 1)

  1. I created two emails.

Email.objects.create(email = u"bla1", person = Person.objects.get(pk = 1))
Email.objects.create(email = u"bla2", person = Person.objects.get(pk = 1))

  1. Try to get the emails of a person:

Person.objects.all()[0].emails.all()[0].email (prints "bla2", instead of "bla1")
Person.objects.all()[0].emails.all()[1].email (prints "bla2")
But,
[x.name for x in Person.objects.all()[0].emails.all()] prints "bla1" and "bla2" (which is the expected result).

Change History (1)

comment:1 Changed 3 years ago by akaariai

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Resolution set to invalid
  • Status changed from new to closed

If I read your description correctly, the error is you are assuming there is an order for the related objects. This is not true if you don't use .order_by(). The related objects are not ordered, unless you order them by some column. The real reason this happens is that in SQL if you do:

select * from sometable offset 1 limit 1;
vs
select * from sometable offset 0 limit 1;

the DB is free to return the same row for the both queries. And you are doing multiple queries exactly like above in your code.

Im marking this as invalid. If I am missing your problem, then reopen this ticket.

Note: See TracTickets for help on using tickets.
Back to Top