【发布时间】:2019-01-13 13:15:26
【问题描述】:
我正在尝试向我的查询集的实例添加一个额外的字段,然后按新字段对集合进行排序。
但我得到一个字段错误(Cannot resolve keyword 'foo' into field. Choices are: ...)
我的观点(摘要):
def view(request):
instances = Model.objects.all()
for counter, instance in enumerate(instances):
instance.foo = 'bar' + str(counter)
instances.order_by('foo') #this line causes trouble
return render(request, 'template.html', {'instances': instance})
我的模板:
{% for instance in instances %}
{{instance.foo}}
{% endfor %}
如果我省略 order_by 行,模板会按预期呈现,因此该字段似乎就在那里。
那么为什么会出现字段错误?
如果有人能帮助我理解我做错了什么,那就太棒了。
提前致谢。
我找到了将模板更改为的可能解决方案
{% for instance in instances|dictsort:'foo' %}
效果很好,但据我了解,视图中的逻辑应该尽可能少,所以我认为应该在视图中进行排序。
或者这实际上是正确的方法?
【问题讨论】:
-
因为它不是一个字段,所以您为对象添加了一个额外的属性。但这没关系。查询集首先处理查询。如果您调用
.order_by,您将在该模型上构造一个新的QuerySet。由于foo不是字段,因此无法对此进行排序。 -
感谢您的回答,这澄清了很多。所以
order_by实际上会导致对数据库的另一个调用,当然该字段不存在,所以我得到了错误。我将如何按新属性排序? - 编辑:刚刚看到你的答案,这就解释了。 -
带有 Python 排序功能,例如
sorted(..)。
标签: python django django-templates django-views django-orm