How to make a Union of two queries using Django Filter

Asked

Viewed 858 times

4

I was racking my brain to do union of two darlings using Django Filter and I ended up doing it on hand (Model.objects.raw("SELECT....")).

How could I union with Django’s ORM?

Note: I have 2 different tables with some common fields.

Table1

  • table1_id
  • name
  • Description
  • created_at
  • user_id

Table2

  • table2_id
  • name
  • Description
  • created_at
  • user_id

The relationship I want to maintain is between user_id. I want to put these records together and sort through created_at.

  • Just to be clear, UNION you mean literally joining the results of one query with the other?

  • Yes, I have 2 different tables with some fields in common. I will edit in the topic.

  • I guess you’d have to make one for, like,: for obj in Table1.objects.all(): result += Table2.objects.filter(user_id=obj.user_id). Works?

  • Between using 2 selects and a .raw I think the .raw right?

  • In terms of performance, believe yes. It is worth taking the test. I think it will depend on the size of your table as well.

3 answers

1

Depending on the type of relationship you are looking for, this can help you:

Table1.objects.filter(user_id__in=[x.user_id for x in Table2.objects.all()]).order_by('created_at')

Anyway, you can test the SQL equivalent of any Django query as follows:

query_aleatoria = Table1.objects.filter(description__contains='abacaxi')
print(query_aleatoria.query) # considerando python 3+

Edit:

I suggest you review your database structure, this user_id It seems to me a good candidate for foreign key, in which case the query would be easier. If you could include your relational model in your question, it would be of great help.

1

0

Another way I found to make it work is by using the chain.

from itertools import chain

query1 = Blog1.objects.all()
query2 = Blog2.objects.all()

posts = list( chain(query1, query2) )

Browser other questions tagged

You are not signed in. Login or sign up in order to post.