Flo
Flo

Reputation: 3047

efficient filter objects in django based on other tables objects

I have two models in django and I want to remove all objects from one table, that match a subset of the other tables params. My Question now is, what is the most efficient way.

The a is around 5000 objects, while b is around 40000 objects.

My current solution looks like this, but that doesn't feel right.

a_with_a_and_b = a.objects.filter(param1='a', param2='b').values('c','d')

for a in a_with_a_and_b:
    _b = b.filter(param3=a['c'],param4=a['d'])
    if _b:
        print('delete it')

Upvotes: 0

Views: 29

Answers (1)

4140tm
4140tm

Reputation: 2088

How about something like this:

list_c = a.objects.filter(param1='a', param2='b').values_list('c', flat=True)
list_d = a.objects.filter(param1='a', param2='b').values_list('d', flat=True)

b.objects.filter(param3__in=list_c, param4__in=list_d).delete()

Upvotes: 1

Related Questions