【问题标题】:how to Insert or update if already exists use Django and SQLITE如果已经存在,如何插入或更新使用 Django 和 SQLITE
【发布时间】:2021-02-01 14:07:00
【问题描述】:

我想在使用Django的SQLite中插入数据,如果数据库中存在数据,则新记录只会更新我的数据库,如果不存在则插入新记录。

class User(models.Model):
    email= models.CharField(max_length=200, unique=True)
    name= models.CharField(max_length=200)
    salary = IntegerField(null=True) 

我尝试使用

try:
     # update codes
except:
     # Insert codes

但失败了,它总是插入和失败,它给我的错误是该电子邮件是唯一的,没有更新现有记录。

我能做什么?

【问题讨论】:

    标签: python django sqlite


    【解决方案1】:

    您可以使用 update_or_create。

    一种使用给定 kwargs 更新对象的便捷方法,必要时创建一个新对象。

    obj, created = User.objects.update_or_create(email='foo@bar.com', name='foo', salary=100)
    

    参考这个https://docs.djangoproject.com/en/3.1/ref/models/querysets/#update-or-create

    【讨论】:

      猜你喜欢
      • 2010-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多