首页 > 解决方案 > 如果存在则更新对象,如果不存在则创建 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() 方法吗?!或者没有更好的方法来实现它吗?我非常感谢你的帮助

标签: pythondjango

解决方案


我猜您想ItemInformation您尝试创建的内容更新所有内容。我会这样做:

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 正在找麻烦。


推荐阅读