Update object in database

Hello everyone,

I have one csv file and I read columns and rows and put them all in new_item_details dictionary. listItem array includes row data and first one is pk.

new_item_details = {}
for i in range(len(listHeader)):
   new_item_details[listHeader[i]] = listItem[i]

What I want to do is that if the pk in the database and the pk in the csv file match (the number of columns can change dynamically in the file), I want to update the values in the database. I wrote a code something like this, but I have an error “no field name key”

new_sample = Samples()
if(Samples.objects.get(pk=listItem[0])):
    for key, value in new_item_details.items():
        Samples.objects.filter(pk=listItem[0]).update(key=value)
else:
    new_sample.__dict__.update(new_item_details)
    new_sample.save()

Do you have any idea where I am making mistakes. Thanks in advance.

Hey there!
The problem is in this block of code.

When you pass .update(key=value) you’re basically saying to the update function:
Update the column key to this value. And this is not specific to django itself, you’re passing key as keyword argument to the function. When you have this kind of scenario, generally you want to do: .update(**{key: value}). Swapping this will make it work.

Are you aware that you’re going to issue a lot of updates to the database with this approach?
The case that you’re trying to solve here looks like a update_or_create scenario.

1 Like

Hey Leandro,

Thanks for your reply. I changed the code as below and it worked well. Do you think it is efficient?

try:
    if(Samples.objects.get(pk=listItem[0])):
       Samples.objects.filter(pk=listItem[0]).update(**new_item_details)
except Samples.DoesNotExist:
       print("Samples DoesNotExist")

You’re getting there.
Did you take a look in the documentation that i sent you in the last reply?

Yes, I looked at it. Instead of setattr(obj, key, value) and for loop, I tried to do it with update but maybe I need to adapt update_or_create() to my code.

Actually that section with the set_attr is showing a example that looks like the one you’re doing here. But it gives a better way of achieving the same result with the update_or_create afterwards.

In the last reply, you weren’t creating the object, do you still want to create one, or just update it?

Yes, I only want to update it according to the date in csv file. So I did something like this and it works fine I believe.

new_sample = Sample()
try:
   if(Samples.objects.get(pk=listItem[0])):
       Samples.objects.filter(pk=listItem[0]).update(**new_item_details)

except Samples.DoesNotExist:
   print("Samples Does Not Exist!")
   new_sample.__dict__.update(new_item_details)
   new_sample.save()

Yeah, that works as well. You may find this snippet more readable.

sample, created = Samples.objects.update_or_create(
    pk=listItem[0],
    defaults=**new_item_details,
)
1 Like

Thank you very much Leandro! It really works well!

1 Like