2013-11-27 23 views
1

更改数据库写一个方法我在Django模型等制成的产品类别:如何,以便直接在Django模型

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) 

,我想添加这个类中的卖出()方法。以及我的确如此:

def sell(self): 
    result = self.quantity - 1 
    return result 

我想在执行P.sell()时更改数据库中的值。

当我运行它,在这样

>>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

呃......

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

我不知道......你为什么要加'如果保存:',而不是自动保存? – yuvi

+1

@yuvi:如果需要在保存之前进一步修改模型属性。 –