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

查看:44
本文介绍了使用 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

这两个模型的字段完全不同,两个模型唯一的共同字段是date"和title"(当然还有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) 两个查询并将它们组合在一个 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天全站免登陆