如果不存在,我正在尝试创建新对象,如果存在,我会更新一些字段,我已经看到了几个答案,但仍然不清楚,我无法很好地实现它这是我的型号.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
,然后我用quantity : 20
再次输入cableXYZ
,它应该更新quantity field to 30
,这很好,但当我尝试输入一个不存在的新对象时,它不会保存对象!在save((方法中,我有没有遗漏要添加的内容?!或者,难道没有更好的方法来实现它吗?!我非常感谢你对的帮助
我猜您想用您试图创建的Information
更新所有Item
。我会这样做:
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)
此外,我发现您的命名方案令人困惑,包含ForeignKey信息的模型Item(称为Item(正在引发麻烦。