Issue
I want to make a query like this:
Student.objects.filter(id= id).update(name=value)
And the value comes from the user.
But the problem is that I'm not only to update name but also update some other information like address or phone number. I don't want to create duplicated codes like:
Student.objects.filter(id= id).update(address=value)
Student.objects.filter(id= id).update(phone_number=value)
I only want to have one line code like:
Student.objects.filter(id= id).update(XXX=XXX_value)
So I wonder if I can assign any variable to the left varaible inside update function or not.
Sorry, the left key is not a certain value. It depends on the user's post. It might be an address or just name next time. It's not a fixed value.
Thanks.
Solution
You can dynamically define the fields by providing them in a dictionary and using **
to unpack the dictionary into arguments for update()
.
fields_to_update = {
"address": address_value,
"phone_number": phonenumber_value,
}
Students.objects.filter(id=update_id).update(**fields_to_update)
Answered By - monkut
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.