如何更新模型中的字段而不在django中创建新记录? [英] How to update fields in a model without creating a new record in django?

查看:105
本文介绍了如何更新模型中的字段而不在django中创建新记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个django中的模型,我只想更新,也就是说,当我调用它并设置数据时,它不会创建一个新的记录,只更新现有的记录。我该怎么做?这是我有的:

  class TemperatureData(models.Model):
date = models.DateTimeField()
value = models.PositiveIntegerField()
alert = models.BooleanField()


解决方案

如果从数据库获取模型实例,则调用save方法将始终更新该实例。例如:

  t = TemperatureData.objects.get(id = 1)
t.value = 999#字段
t.save()#这将只更新

如果您的目标是防止任何INSERT,那么你可以覆盖 save 方法,测试主键是否存在并引发异常。有关详细信息,请参阅以下内容:




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()

解决方案

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:

这篇关于如何更新模型中的字段而不在django中创建新记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆