Opened 7 years ago

Closed 7 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: sean.dong 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:

Description

>>> 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 Gaynor

Triage Stage: UnreviewedAccepted

comment:2 Changed 7 years ago by Bruno Renié

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',
                                              'feed__category__color')

then:

for e in entries:
    print e.feed.category.color # prints datetime.datetime instances (all the same) - related user's creation date
    print e.feed.category.id # 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 Russell Keith-Magee

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

comment:4 Changed 7 years ago by Russell Keith-Magee

milestone: 1.2

comment:5 Changed 7 years ago by Russell Keith-Magee

Resolution: duplicate
Status: newclosed

Duplicate of #12851, fixed in r12817.

comment:6 Changed 5 years ago by Jacob

milestone: 1.2

Milestone 1.2 deleted

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