通过@property订购Django queryset [英] Ordering Django queryset by an @property
问题描述
我试图通过在模型中定义的属性来排序查询集,但不能确定最佳的方法。这是以下属性:
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
基本上,我想做一个:
things = Thing.objects.all().order_by('-name')
但当然,在呈现时会获得一个Caught FieldError:无法将关键字'name'解析为字段
but of course getting a Caught FieldError while rendering: Cannot resolve keyword 'name' into field.
任何想法?
编辑:我明白我不能这样排序 @property
不是数据库字段。我的问题是如何排序,因为 @property
不是数据库字段。
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.
推荐答案
您不能这样做,因为该属性不在MySQL中,而是在您的python代码中。如果你真的想这样做,你可以在客户端(虽然会很慢):
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)
这篇关于通过@property订购Django queryset的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!