Order_by foreignkey that can be null (after QS-RF branch merged)

42 views
Skip to first unread message

Rudolph

unread,
May 23, 2008, 8:08:59 AM5/23/08
to Django users
Hi,

I encountered a change in the ordering when using Django after the
queryset-refactor branch merged. When ordering by a foreignkey which
can be null, all items with this key being null get excluded. Example:

class Foo(models.Model):
name = models.CharField...

class Bar(models.Model):
name = models.CharField...

class Bas(models.Model):
foo = models.ForeignKey(Foo)
bar = models.ForeignKey(bar, null=True, blank=True)

class Meta:
ordering = ('foor', 'bar')

Items in Bas that do not have "bar" defined seem to disapear. In the
admin interface a can see these items in the list view (because it
only orders on the first field?), but when I click them for editing I
get a 404. Also in my view, using the default ordering all the items
that do not have "bar" disappear.
Is this expected behaviour or a bug?

Thanks,

Rudolph

Rudolph

unread,
May 23, 2008, 8:17:01 AM5/23/08
to Django users
A small clearification to the previous post: by disappear I mean they
are not in the queryset. They stay in the database ofcourse.

Thanks

Karen Tracey

unread,
May 23, 2008, 10:26:05 AM5/23/08
to django...@googlegroups.com

First, I believe your ordering specification has to actually access a field in the related model (i.e., be something like ('foo__name', 'bar__name')  in order for the problem to arise.  Ordering just by ('foo', 'bar') works fine (but there you are ordering by their primary key IDs, which doesn't tend to be terribly useful in general).  When you add in access to a field, the ORM has to join in the related table, and since it uses an inner join for this you get 'dropped' records from Bas.  This has been reported as a problem:

http://code.djangoproject.com/ticket/7181

but that ticket hasn't been reviewed yet so no feedback on if/how it will be fixed.

The issue of the admin returning a 404 when you try to edit one of the objects that has null for the ForeignKey probably has the same root cause.  I verified the query resulting from the admin trying to look up by primary key is also using an inner join to all the related tables but didn't track it any farther than that.

Karen

Rudolph

unread,
May 23, 2008, 10:36:10 AM5/23/08
to Django users
Thanks. You are right, my actual code ordered by a specific field but
I kept the example simple because it shows the same problem. Thanks
for the link to the ticket because I could not find a ticket for it
myself.

Rudolph
Reply all
Reply to author
Forward
0 new messages