[英]How can I show data one after another in django models
I am Using Django Framework in my project. 我在我的项目中使用Django Framework。 I want the results that start with query first then results that contain query next but when I am using the following code it is giving mixed results instead of one after other.
我想要以查询开头的结果,然后是包含查询的结果,但是当我使用以下代码时,它给出的是混合结果,而不是一个接一个。 How can I achieve My requirement
我如何达到我的要求
collections = TokenCollection.objects.filter(Q(title__istartswith=query) | Q(title__icontains=query))
Something using itertools.chain
might suit your needs, but you might run into performance problems if the returned dataset is large: 使用
itertools.chain
可能适合您的需求,但是如果返回的数据集很大,则可能会遇到性能问题:
from itertools import chain
collections = list(chain(
TokenCollection.objects.filter(title__istartswith=query),
TokenCollection.objects.filter(title__icontains=query)
.exclude(title__istartswith=query)
))
Try this 尝试这个
from django.db.models import Q, Case, Value, IntegerField
TokenCollection.objects.filter(
Q(title__istartswith=query) | Q(title__icontains=query)
).annotate(
c=Case(
When(title__istartswith=query, then=Value(1)),
When(title__icontains=query, then=Value(2)),
output_field=IntegerField())
).order_by('c')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.