Using django how can I combine two queries from separate models into one query?

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

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

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

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.

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

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.


I would suggest that you use Model inheritance.

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.

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.

Need Your Help

conversion to proper postfix notation in minimum number of steps

algorithm postfix-notation

An expression consisting of operands and binary operators can be written in Reverse Polish Notation (RPN) by writing both the operands followed by the operator. For example, 3 + (4 * 5) can be writ...

UNION ALL two SELECTs with different column types - expected behaviour?

sql standards sqldatatypes union-all

What is the expected behaviour due to SQL Standard when we perform UNION on two tables with different data types: