Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering Django queryset by a @property [duplicate]

Tags:

python

django

I'm trying to order a query set by a property I defined in the model, but not sure the best way to do this. Here's the property:

@property
def name(self):
    if self.custom_name:
        return self.custom_name
    else:
        return self.module_object.name

Essentially, I'd like to do a:

things = Thing.objects.all().order_by('-name')

but of course getting a Caught FieldError while rendering: Cannot resolve keyword 'name' into field.

Any ideas?

EDIT: I understand that I can't sort this way because the @property isn't a database field. My question is how to sort given that @property isn't a database field.

like image 739
Brenden Avatar asked Dec 12 '11 17:12

Brenden


3 Answers

You can't do that because that property is not in MySQL, but in your python code. If you really want to do this, you can on the client-side(though it will be very slow):

sorted(Thing.objects.all(), key=lambda t: t.name)
like image 184
Gabi Purcaru Avatar answered Oct 20 '22 15:10

Gabi Purcaru


order_by happens on the sql level, so it can't make use of properties, only field data.

have a look at the queryset api, you may be able to make use of e.g. extra to annotate your query and sort on that

like image 4
second Avatar answered Oct 20 '22 15:10

second


Have a look at django-denorm. It lets you maintain calculated values in the database (which you can then use to sort efficiently) for the cost of a single method decorator.

like image 4
Evan Brumley Avatar answered Oct 20 '22 14:10

Evan Brumley