0

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')
0

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

2 Comments

I need an exact combination of d and c. the __in would combine all possibilities, right? I.e. if a are names like john doe and paul rich it would find the name paul doe in b, right?
The end result would be identical to your example. It's the same filtering criteria for a and the resulting to sequences would contain the same values as in the dicts when using .values('c','d'). By using __in you just offload the iteration to the database.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.