通过 @property 对 Django 查询集进行排序
我正在尝试按我在模型中定义的属性来排序查询集,但不确定执行此操作的最佳方法。这是属性:
@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:无法将关键字“名称”解析为字段。
有什么想法吗?
编辑:我知道我无法以这种方式排序,因为 @property
不是数据库字段。我的问题是鉴于 @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
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你不能这样做,因为该属性不在 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):
order_by
发生在 sql 级别,因此它不能使用属性,只能使用字段数据。看看 查询集api,您可以使用例如
extra
来注释您的查询并对其进行排序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看看 django-denorm。它允许您在数据库中维护计算值(然后您可以使用它来有效排序),而只需花费单个方法装饰器的成本。
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.
您只能按数据库字段排序。您可以提取所有记录,将它们转换为列表,然后对它们进行排序,尽管这可能效率低下且缓慢。
或者您可以添加一个名为
name
的数据库字段,并通过保存后挂钩填写它;然后您可以使用order_by
对其进行排序。You can only order by database fields. You can pull all records, turn them into a list, and sort them, although that may be inefficient and slow.
Or you can add a database field called
name
and fill it in via a post-save hook; then you can sort it usingorder_by
.