Friday, April 25, 2014

Django explicit `order_by` by ForeignKey field

Hi. So I have some small models:

class Group(models.Model):
    name = models.CharField()
    
    class Meta:
        ordering = ('name',)

class Entity(models.Model):
    name = models.CharField()
    group = models.ForeignKey(Group, null=True)

Now I want to perform a really simple query like this:

SELECT * FROM `app_entity`
WHERE `app_entity`.`name` = 'something'
ORDER_BY `app_entity`.`group_id` ASC;

Note that I really want to order by the field itself with no useless joins or smth else. So I write smth like that:

Entity.objects.filter(name='something').order_by('group')

and django happily makes this query:

SELECT `app_entity`.`id` FROM `app_entity`
LEFT OUTER JOIN `app_group` ON ( `app_entity`.`group_id` = `app_group`.`id` )
WHERE `app_entity`.`name` = 'smth' 
ORDER BY `app_group`.`name` ASC

According to the docs it uses default Group model ordering and this default behaviour makes sense.
And I need this ordering to be set (for admin and some other places).
If I don't set ordering param in Group.Meta - I get what I want: explicit query shown above (1st one).
But as I said I need it. And I just can't get this query easily.
So we have some sort of inconsistant behaviour - I can do the right thing without ordering param and I can't do it with it.

order_by('group_id') doesn't work and raises FieldError.
For now I'm using extra(order_by=['app_entity.group_id']) or even order_by('app_entity.group_id') but it's quite ugly and it's still such a trivial thing that should have a simple and straight ORM solution.

As I think this might be considered as a bug or smth. In django sourses I found some place where field names lile `group_id` work.
For example, `values_list` method. But this behaviour is marked as a hack there.

So the first question is whether do I miss smth and it can be done somehow.
And the second, if not, do I need to submit a ticket for this.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/c7ff4b2f-da66-40e8-b83d-5135efe81e0b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment