python - 如果存在则更新对象,如果不存在则创建 django
问题描述
我正在尝试创建新对象(如果不存在)并更新某些字段(如果存在),我已经看到了几个答案,但仍然不清楚,我无法很好地实现它这是我的 models.py
class Information(models.Model):
name = models.CharField(max_length=50,unique=True)
def __str__(self):
return self.name
class Item(models.Model):
item = models.ForeignKey(Information,on_delete=models.CASCADE)
quantity = models.IntegerField()
quantity_storage = models.IntegerField(blank=True)
buying_price = models.DecimalField(max_digits=30,decimal_places=3)
def __str__(self):
return self.item.name
def save(self,*args,**kwargs):
if self.item:
Item.objects.filter(item__name=self.item).update(
quantity=F('quantity') + self.quantity
else:
super(Item,self).save(*args,**kwargs)
如果对象已经存在,我必须更新quantity
字段,例如我已经输入item :cableXYZ , quantity : 10
然后我cableXYZ
再次输入quantity : 20
它应该更新quantity field to 30
这工作正常,但是当我尝试输入一个不存在的新对象时,它不会保存对象!有什么我错过的东西要添加到 save save() 方法吗?!或者没有更好的方法来实现它吗?我非常感谢你的帮助
解决方案
我猜您想Item
用Information
您尝试创建的内容更新所有内容。我会这样做:
def save(self,*args,**kwargs):
items = Item.objects.filter(item=self.item)
if items: # if some items are found in the database
items.update(quantity=F('quantity') + self.quantity)
else:
return super(Item,self).save(*args,**kwargs)
另外,我发现您的命名方案令人困惑,包含名为 item 的 ForeignKey Information 的模型 Item 正在找麻烦。
推荐阅读
- php - PHP:为什么我的变量在我将它们包含在请求语句中后不可用?
- javascript - 无法使用formdata将文件发送到rails后端的ruby
- loops - 从函数/模块中提取 llvm 位码中的循环
- php - Laravel:试图获取非对象的属性“符号”
- angular - Angular 7 Reactive forms“具有未指定名称属性的表单控件没有值访问器”
- docker - kubeadm init [恐慌:分配给 nil 映射中的条目]
- angular - 将 CSS 类应用于组件标签
- python - Keras/Tensorflow中dropout的动态切换
- powershell - 如何调用 Jenkins API 并使用 powershell 发送自定义参数
- sql - 行聚合的案例语句