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

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

问题描述



我的模型很像:

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

我在数据库元组中像这样:

  1 BOSTON新波士顿
2纽约纽约NY $ b 3 NEWTON旧的杂志Mass
4 ANEWVIEW年轻人的看法

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




  • 首先是$ {code>的名称,以字符串

  • 开始,然后开始代码使用字符串

  • ,然后包含字符串

  • 名称然后代码包含字符串



所以上一个列表应该以下列方式出现:

  2纽约NYT纽约日记
3 NEWTON旧的杂志Mass
1波士顿新波士顿
4 ANEWVIEW年轻人的看法

我发现有这样的结果的唯一方法是进行不同的搜索(如果我在一个搜索中放置OR,我放弃了我想要的顺序)。



我的问题是显示结果的模板的代码是非常多余的,并且诚实地非常丑陋,因为我必须为所有4个不同的查询重复相同的代码。最糟糕的是我不能使用分页!



现在,由于不同查询的结构是一样的,所以如果有办法加入4个查询器,并给出模板只有一个查询器。

解决方案

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

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

但这似乎不太好,因为你必须查询。



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

  Serials.objects.raw(sql_string)

另请查看:



如何在Django视图中组合2个以上的查询?


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

My model is almost like:

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

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

  • first the names that start with the string
  • then the codes that start with the string
  • then the names that contain the string
  • then the codes that contain the string

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

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).

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!

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.

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

Serials.objects.raw(sql_string)

Also look at this:

How to combine 2 or more querysets in a Django view?

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

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