vp_5614
vp_5614

Reputation: 41

How to do DB update in a single query in django when using an IF condition?

I have the following code -

 testcase = Table1.objects.filter(ID=id,serialno ='1234', condition='False').exists()
 if not testcase:
     c = Table1.objects.filter(ID=id,serialno ='1234').select_for_update().update(condition='True')

Here, I am querying the same DB twice. Is there any way where I can do the filter exists and update in a single query?

Upvotes: 1

Views: 95

Answers (2)

Andrey Borzenko
Andrey Borzenko

Reputation: 738

Filtering doesn't send a query. I agree with the answer above, but if you want a correction for you code, then this would be correct:

testcase = Table1.objects.filter(ID=id,serialno ='1234')
if not testcase.filter(condition='False'):
     c = testcase.select_for_update().update(condition='True')

Upvotes: 1

Arjun Shahi
Arjun Shahi

Reputation: 7330

You can just use the update method with your filter query.

Table1.objects.filter(ID=id,serialno ='1234', condition='False').update(condition=True)

Upvotes: 0

Related Questions