Opened 7 years ago

Closed 6 years ago

Last modified 5 years ago

#11606 closed (duplicate)

return error data when using only() and select_related() at the same times that models foreign key is set to default null.

Reported by: seandong Owned by: nobody
Component: Database layer (models, ORM) Version: master
Severity: Keywords: only, select_related, defer
Cc: buburno+django@… Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: UI/UX:


>>> from station.models import Station_Building
>>> s1=Station_Building.objects.select_related('building').only('azimuth','building__level').filter(building__isnull=False)
>>> s1[0].building.level
0 #wrong value
>>> s1=Station_Building.objects.select_related('building').filter(building__isnull=False)
>>> s1[0].building.level
1 #right value

Change History (6)

comment:1 Changed 7 years ago by Alex

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Triage Stage changed from Unreviewed to Accepted

comment:2 Changed 7 years ago by brutasse

  • Cc buburno+django@… added

I have tried to look at this without success. It seems that the generated SQL is perfectly fine but some columns get mixed when building the python representation.

I have some models that looks like this:

class Category(models.Model):
    color = models.CharField(max_length=50)

class Feed(models.Model):
    name = models.CharField(max_length=255)
    category = models.ForeignKey(Category, related_name='feeds')

class Entry(models.Model):
    feed = models.ForeignKey(Feed, related_name='entries')
    title = models.CharField(max_length=255)
    date = models.DateTimeField()
    read = models.BooleanField(default=False, db_index=True)
    user = models.ForeignKey(User, related_name='entries')

If I do:

entries = Entry.objects.select_related().only('id', 'feed', 'title', 'date',
                                              'read', 'feed__name',


for e in entries:
    print e.feed.category.color # prints datetime.datetime instances (all the same) - related user's creation date
    print # prints the related user's password hash sha1$cf481$01b13cdfab3.....

So, the problem may not be specific to foreign keys, and the engine fetches information from wrong related tables.
This happens at least on PostgreSQL, I can't confirm on other backends.

comment:3 Changed 7 years ago by russellm

#11844 seems to be a duplicate, with another test case.

comment:4 Changed 7 years ago by russellm

  • milestone set to 1.2

comment:5 Changed 6 years ago by russellm

  • Resolution set to duplicate
  • Status changed from new to closed

Duplicate of #12851, fixed in r12817.

comment:6 Changed 5 years ago by jacob

  • milestone 1.2 deleted

Milestone 1.2 deleted

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