我试图在DATABASE中创建一行,如果存在,则使用DJANGO将旧值更新为new + old。类似PHP的东西:
$sql= "IF EXISTS(SELECT * FROM April_sales WHERE label='".$product."') THEN
BEGIN
UPDATE francais SET sold=sold+'".$sold."' WHERE label='".$product."';
END;
ELSE
BEGIN
INSERT INTO April_sales (sold,sold) VALUES('".$sold."','".$product."');
END;
END IF;";
我正在接收新行,尝试此操作:
query = April_sales.objects.get_or_create(product=product, sold= new_amount, date= timezone.now())
sum_value = query.sold + new_amount
query = April_sales(product=product, sold=sum_value , date=timezone.now())
query.save()
答案 0 :(得分:0)
我找到了以下解决方案,它不漂亮而且有点长: 如果有人有更好的建议,请随时改进。
try:
query = April_sales.objects.get(product=product)
query.sold = query.sold + new_amount
query.date = timezone.now()
query.save()
except April_sales.DoesNotExist:
query = April_sales(product=product, sold=new_amount, date=timezone.now())
query.save()
答案 1 :(得分:0)
get_or_create
总是返回一个元组,你需要两个变量来捕捉你想要的东西:
试试这个:
query, created = April_sales.objects.get_or_create(product=product)
if created:
query.sold = new_amount
else:
query.sold += new_amount
query.date = timezone.now()
query.save()