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.
CodePudding user response:
As per update docs
You can update multiple fields — there’s no limit on how many
So the following should do
Student.objects.filter(id=id).update(address=address_value, phone_number=phone_number_value)
EDIT
left variable is not a fixed item. It could be address or just be phone_number
In that case populate a dict dynamically and then unpack it in update
. See an example below (your conditions may be of course different).
fields_to_update = {}
if address_value:
fields_to_update["address"] = address_value
if phone_number_value:
fields_to_update["phone_number"] = phone_number_value
Student.objects.filter(id=id).update(**fields_to_update)
Another alternative is to not use update
but to work with a Student
instance directly.
student = Student.objects.get(id=id)
if address_value:
student.address = address_value
if phone_number_value:
student.phone_number = phone_number_value
student.save()
Be aware that student = Student.objects.get(id=id)
can raise DoesNotExist
if a student with the given id is not found.
CodePudding user response:
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)