How to pair two queries using Django Filter

2

I was breaking my head to make union of two queries using Django Filter and ended up doing it on the same hand ( Model.objects.raw("SELECT....") ).

How could I do union with Django's ORM?

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

Table1

  • table1_id
  • name
  • description
  • created_at
  • user_id

Table2

  • table2_id
  • name
  • description
  • created_at
  • user_id

The relationship I want to keep is between user_id . I want to merge these records and sort by created_at .

    
asked by anonymous 14.12.2017 / 21:44

1 answer

0
___ erkimt ___ How to pair two queries using Django Filter ______ qstntxt ___

I was breaking my head to make user_id of two queries using Django Filter and ended up doing it on the same hand ( %code% ).

How could I do %code% with Django's ORM?

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

Table1

  • table1_id
  • name
  • description
  • created_at
  • user_id

Table2

  • table2_id
  • name
  • description
  • created_at
  • user_id

The relationship I want to keep is between %code% . I want to merge these records and sort by %code% .

    
______ ___ azszpr290652

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

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

Either way, you can test the equivalent in any SQL query in Django 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 %code% % seems a good foreign key candidate, in which case, the query would be easier. If you can include your relational model in your question, it would be helpful.

    
___
12.04.2018 / 00:20