如何编写一个方法以直接在Django模型中更改数据库

时间:2013-11-27 21:45:00

标签: django django-models

我在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()

它可以将数量更改为9

但是当我输入p.sell()时,我怎么才能改变这个值? 我怎么能在模特中编辑它?

1 个答案:

答案 0 :(得分:1)

嗯...

def sell(self, save=True):
  self.quantity -= 1
  if save:
    self.save()