Ev.
Ev.

Reputation: 1567

How to do a filter with a queryset result Django

I was wondering if it is possible to filter a queryset result with a queryset object attribute.

Example:

clients = Client.objects.filter(name__contains=search)

This should return several objects

result = Invoice.objects.filter(client_id=clients.id)

Now I want all the data inside Invoice that corresponds to the clients.id found.

What is the most optimized way to do it? Since Django is a powerful framework, I was wondering if it has a good and fast way to do it without me having to add the primary result to a list and do a for loop.

Upvotes: 0

Views: 1488

Answers (2)

GwynBleidD
GwynBleidD

Reputation: 20539

You don't even need to extract ID from clients, that will work just fine:

clients = Client.objects.filter(name__contains=search)
result = Invoices.objects.filter(client__in=clients)

It will result in SQL query:

SELECT * FROM invoices WHERE result.client_id IN (SELECT `id` FROM `client` WHERE ...)

Upvotes: 1

Akisame
Akisame

Reputation: 774

You can do this by filtering directly Invoices using lookups

result = Invoice.objects.filter(client__name__contains=search)

Alternatively, you can find all clients, extract ids, and filter invoices by those id.

clients = Client.objects.filter(**your_crazy_search).values_list('id', flat=True).all()
result = Invoices.objects.filter(client_id__in=clients_id)

Upvotes: 2

Related Questions