我在Django模型中创建了一个Product类,如:
class Product(models.Model):
title = models.CharField(max_length=255, unique = True)
description = models.TextField()
image_url = models.URLField(verify_exists=True, max_length=200, blank = True, null = True)
quantity = models.PositiveSmallIntegerField(default=0)
我想在这个类中添加一个sell()方法。我确实喜欢:
def sell(self):
result = self.quantity - 1
return result
我想在执行P.sell()时更改数据库中的值。
当我在shell中运行它时,就像这样
>>p = Product(title = 'title', description = 'des', quantity = 10)
>>p.save()
>>p.sell()
9 # it shown 9, but the database not changed still 10
>> p.quantity = p.sell()
>> p.save()
但是当我输入p.sell()时,我怎么才能改变这个值? 我怎么能在模特中编辑它?
答案 0 :(得分:1)
嗯...
def sell(self, save=True):
self.quantity -= 1
if save:
self.save()