Django:同一模型上不同查询集的联合 [英] Django: union of different queryset on the same model

查看:21
本文介绍了Django:同一模型上不同查询集的联合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在对模型进行搜索编程,但遇到了问题.

I'm programming a search on a model and I have a problem.

我的模型几乎像:

class Serials(models.Model):
    id = models.AutoField(primary_key=True)
    code = models.CharField("Code", max_length=50)
    name = models.CharField("Name", max_length=2000)

我在数据库中有这样的元组:

and I have in the database tuples like these:

1   BOSTON   The new Boston
2   NYT      New York journal
3   NEWTON   The old journal of Mass
4   ANEWVIEW The view of the young people

如果我搜索字符串new,我想要的是:

If I search for the string new, what I want to have is:

  • 首先是以字符串开头的names
  • 然后是以字符串开头的codes
  • 然后是包含字符串的 names
  • 然后是包含字符串的 codes

所以之前的列表应该以如下方式出现:

So the previous list should appear in the following way:

2   NYT      New York journal
3   NEWTON   The old journal of Mass
1   BOSTON   The new Boston
4   ANEWVIEW The view of the young people

我发现获得这种结果的唯一方法是进行不同的搜索(如果我在一次搜索中输入OR",就会失去我想要的顺序).

The only way I found to have this kind of result is to make different searches (if I put "OR" in a single search, I loose the order I want).

我的问题是显示结果的模板代码真的是多余的,老实说非常难看,因为我必须为所有 4 个不同的查询集重复相同的代码.而且更糟糕的是我不能使用分页!

My problem is that the code of the template that shows the result is really redundant and honestly very ugly, because I have to repeat the same code for all the 4 different querysets. And the worse thing is that I cannot use the pagination!

现在,由于不同查询集的结构是相同的,我在徘徊是否有办法加入 4 个查询集并只给模板一个查询集.

Now, since the structure of the different querysets is the same, I'm wandering if there is a way to join the 4 querysets and give the template only one queryset.

推荐答案

您可以进行这四个查询,然后将它们链接到您的程序中:

You can make those four queries and then chain them inside your program:

result = itertools.chain(qs1, qs2, qs3, qs4)

但这似乎不太好,因为您必须进行查询.

but this doesn't seem to nice because your have to make for queries.

你也可以使用raw sql编写自己的sql,例如:

You can also write your own sql using raw sql, for example:

Serials.objects.raw(sql_string)

也看看这个:

如何组合 2 个或更多查询集在 Django 视图中?

这篇关于Django:同一模型上不同查询集的联合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆