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

后端 未结 5 1664
你的背包
你的背包 2020-12-23 11:14

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 th

5条回答
  •  死守一世寂寞
    2020-12-23 11:46

    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

提交回复
热议问题