Friday, April 25, 2014

Re: Django explicit `order_by` by ForeignKey field

The issue was referenced in #19195 and it was suggested we add the ability to order by field name and not only by attribute name.

I suggest you open a ticket for this and add a reference to it in #19195.

In the mean time you can get the correct ordering by issuing a order_by('group__pk') but you'll have to live with the extraneous JOIN.

Thanks,
Simon

Le vendredi 25 avril 2014 18:50:55 UTC-4, alTus a écrit :
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/cab3da8e-b88b-4e2e-b4fb-febb411ae658%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment