简体   繁体   English

如何在Django模型中一个接一个地显示数据

[英]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)
                           .exclu‌​de(title__istartswit‌​h=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.

相关问题 Django:如何显示两个或三个模型的数据 - Django: how can i show the data of two or three models 使用 models.Model, [(models.Model) ---> (BaseModel)] 创建一个模型后如何继承另一个模型 - How can I inherit another model after creating one with models.Model, [(models.Model) ---> (BaseModel)] 如何在 django 中显示模型数据 - how can I display models data in django 如何在Django中显示来自2个模型的数据并在模板中进行一对多的关联 - how to show data from 2 models in django with one to many relashion in template 如何将数据从一个Django应用程序发送到另一个? - How can I send data from one Django application to another? 如何在 django 中调用/引用相同模型中的另一个属性 - How can I call/refer to another property in the same models in django 在模板中显示另一个数据库的数据,而不是来自 django 模型 - Show data of another database in templates, not from django models 在我向其中一个模型添加新字段后,无法迁移到 django 应用程序 - Can't make migrations to django app after i added a new field to one of the models Django - 将模型相互关联 - Django - Associating models with one another 我们如何从 django 更新一对一的关系模型数据库数据? - how can we update one to one relationship models db data from django?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM