Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update model django through kwargs

Tags:

How can i pass a dict which contain fields to update a Django model? This is not to create an object, but to update it.

example:

obj = Object.objects.create(index=id, **fields) 
like image 352
Pol Avatar asked Nov 05 '10 17:11

Pol


People also ask

How do I update model fields in Django?

Method 2: Using F Expression You can also use the F expression to do the same job. Note: You have to import the F expression before using it. Basically, these are the two methods you can use to update field in Django model.

What is __ str __ in Django?

The __str__ method in Python represents the class objects as a string – it can be used for classes. The __str__ method should be defined in a way that is easy to read and outputs all the members of the class. This method is also used as a debugging tool when the members of a class need to be checked.

How Django knows to update VS insert?

The doc says: If the object's primary key attribute is set to a value that evaluates to True (i.e. a value other than None or the empty string), Django executes an UPDATE. If the object's primary key attribute is not set or if the UPDATE didn't update anything, Django executes an INSERT link.

What is Get_absolute_url in Django?

Django documentation says: get_absolute_url() method to tell Django how to calculate the canonical URL for an object.


1 Answers

As long as the PK is the same, the existing row will be overwritten.

obj = Object(index=id, **fields) obj.save() 
like image 52
Ignacio Vazquez-Abrams Avatar answered Sep 19 '22 21:09

Ignacio Vazquez-Abrams