使用django如何将来自不同模型的两个查询组合成一个查询? [英] Using django how can I combine two queries from separate models into one query?

查看:80
本文介绍了使用django如何将来自不同模型的两个查询组合成一个查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的具体情况下,我有两种消息,我需要检索和分页。

In my specific case, I have two kinds of "messages" that I need to retrive and paginate.

让我们省略细节,只要说第一个在一个称为Msg1的模型中,另一个称为Msg2

Let's omit the details, and just say that the first kind is in a model called Msg1 and the other is called Msg2

这两个模型的字段是完全不同的,两个模型共有的唯一字段是日期和标题(当然,id)。

The fields of these two models are completely different, the only fields that are common to the two models are "date" and "title" (and of course, id).

我可以得到 Msg1.objects.all() Msg2.objects.all()但是我可以将这两个查询组合成一个查询,按日期排序,并分页吗?

I can get Msg1.objects.all() and Msg2.objects.all() but can I combine these two queries into one query, sort it by date, and paginate it?

我需要保留查询的懒惰性质。

I need to preserve the lazy nature of the query.

这个简单的解决方案是 list(query) / code>这两个查询并将它们组合在一个python列表中。但是由于明显的原因,这是无效率的。

The trivial solution is to list(query) both queries and combine them in a python list. but this is inefficient for obvious reasons.

我查看了模型和dp-api上的django引用,但似乎没有一种组合查询的方法不同的模型/表格成一个。

I looked through the django references on models and dp-api, but it doesn't seem that there is a way to combine queries of different models/tables into one.

推荐答案

我建议您使用模型继承

创建包含日期和标题的基本模型。子类Msg1和Msg2如下所述。使用基本模型进行所有查询(填写页面),然后在最后一刻切换到派生类型。

Create a base model that contains date and title. Subclass Msg1 and Msg2 off it as described. Do all your queries (to fill a page) using the base model and then switch to the derived type at the last moment.

继承的真正好处是,django然后允许您在其他模型的外键中使用基本模型,因此可以使您的整个应用程序更加灵活。在引擎盖下,它只是一个表的基础模型,每个子模型的表格包含一对一的键。

The really great thing about inheritance is that django then allows you to use the base model in foreign keys from other models, so you can make your whole application more flexible. Under the hood it is just a table for the base model with a table per sub-model containing one-to-one keys.

这篇关于使用django如何将来自不同模型的两个查询组合成一个查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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