SLATER
SLATER

Reputation: 683

Django: how to update multiple records?

I need to update multiple records (rows) in a table.

First, I get informations to select rows to be update:

ran_st1 = 1
ran_st2 = 1
ran_bra = 'A'
pay_ide = 'FR'
bra_lib = 'Polyvitamines et oligo-éléments'

Then, I select rows to be updated:

rows= Randomisation.objects.filter(Q(ran_st1 = ran_st1) & Q(ran_st2 = ran_st2) & Q(ran_bra = ran_bra) & Q(pay_ide = pay_ide))

And then, I though to make a loop like that, but not sure:

for row in rows:
    r = get_object_or_404(Randomisation, ran_ide = row.ran_ide)
    r.ran_act = 1
    r.save()

Upvotes: 1

Views: 1742

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477883

You can update with .update(..) [Django-doc]:

Randomisation.objects.filter(
    ran_st1=ran_st1,
    ran_st2 = ran_st2,
    ran_bra = ran_bra,
    pay_ide = pay_ide
).update(ran_act=1)

This will work with a query that looks like:

UPDATE randomisation
SET ran_act = 1
WHERE ran_st1 = 1
  AND ran_st2 = 1
  AND ran_bra = 'A'
  AND pay_ide = 'FR'
  AND bra_lib = 'Polyvitamines et oligo-elements'

This is thus done in one query, not in several queries where you each time fetch an element, update that element, and then make an update query to the database for that specific record.

Upvotes: 1

Related Questions