通过@property订购Django queryset [英] Ordering Django queryset by a @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屋!