首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >update object if exists和create if not exists

update object if exists和create if not exists
EN

Stack Overflow用户
提问于 2021-05-26 04:10:46
回答 1查看 276关注 0票数 1

我正在尝试创建新的对象,如果它不存在,并更新一些字段,如果它存在,我已经看到了几个答案,但仍然不清楚,我不能很好地实现它这是我的models.py

代码语言:javascript
运行
复制
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 save()方法中遗漏了什么?!难道没有更好的方法来实现它吗?!我非常感谢你的帮助

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-05-26 06:45:59

我猜你想用你想要创建的Information更新所有的Item。我会这样做:

代码语言:javascript
运行
复制
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信息的模型项是在自找麻烦。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67695007

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档