darkhorse
darkhorse

Reputation: 8722

How to query 2 different tables with only one query in Django?

I have two models called One and Two. Both models have an attribute called producer. I am querying them using the following code:

>>> from itertools import chain
>>> from django.db import connection
>>> producer = 'something'
>>> a = One.objects.filter(producer=producer)
>>> b = Two.objects.filter(producer=producer)
>>> results = list(chain(a, b))
>>> len(connection.queries)
2

Unfortunately, this approach hits my database twice, as the length shows. How can I do this using just one single query. I have lots of different models, and I want to query them all at once in a view. Hitting the database once will greatly help performance. I have no need to sort anything, and the filters themselves are the same for all the models.

Edit: Due to an answer below, I feel its wise to add this, my models look like this:

class Number(models.Model):
     producer = models.CharField(max_length=255)

     class Meta:
         abstract = True

class One(Number):
     ...

class Two(Number):
     ...

Upvotes: 0

Views: 462

Answers (1)

NS0
NS0

Reputation: 6096

There's no way, as far as I'm aware, to directly accomplish that.

One approach that might work, however, is to build your models in a way where they both share this field from a model they inherit. For example:

class Number(models.Model):
    # common fields among objects of type One, Two, etc
    producer = ...

class One(Number):
    # other exclusive fields specifically for objects of type One

class Two(Number):
    # other exclusive fields specifically for objects of type Two

Then you would be able to query the Number model directly with

Number.objects.filter(producer=producer)

to obtain all the results for all objects, whether they are type One or Two.

Although note that making two queries for getting data from two tables is not necessarily a bad thing, and unless the amount of queries you end up with is significantly large/the different models do have a lot in common, it might not be worth the trouble.

Upvotes: 2

Related Questions