Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update fields in a model without creating a new record in django?

I have a model in django that I want to update only, that is, when I call it and set the data, it will not create a new record, only update the existing one. How can I do this? Here is what I have:

class TemperatureData(models.Model):        date = models.DateTimeField()        value = models.PositiveIntegerField()        alert = models.BooleanField() 
like image 203
Ruben Quinones Avatar asked Sep 10 '10 00:09

Ruben Quinones


People also ask

How do I update an existing record in Django?

To update a record, we need the ID of the record, and we need a template with an interface that let us change the values. First we need to make some changes in the index. html template.

How do I update a specific field in Django?

Use update_fields in save() If you would like to explicitly mention only those columns that you want to be updated, you can do so using the update_fields parameter while calling the save() method. You can also choose to update multiple columns by passing more field names in the update_fields list.

How do I add a field to an existing model in Django?

To answer your question, with the new migration introduced in Django 1.7, in order to add a new field to a model you can simply add that field to your model and initialize migrations with ./manage.py makemigrations and then run ./manage.py migrate and the new field will be added to your DB.

How does Django update data?

Update View refers to a view (logic) to update a particular instance of a table from the database with some extra details. It is used to update entries in the database. So Update view must display the old data in the form and let user update the data from there only.


1 Answers

If you get a model instance from the database, then calling the save method will always update that instance. For example:

t = TemperatureData.objects.get(id=1) t.value = 999  # change field t.save() # this will update only 

If your goal is prevent any INSERTs, then you can override the save method, test if the primary key exists and raise an exception. See the following for more detail:

  • How Django knows to UPDATE vs. INSERT
like image 176
ars Avatar answered Sep 24 '22 23:09

ars