views:

78

answers:

3

Hello, assume I have this little model:

class Deal(models.Model):
    purchases = models.IntegerField(default=0)#amount of purchases so far

    increase_purchases(self,to_add):
        self.update( purchases =self.purchases + to_add)

when I try to use this increase_purchases model from shell:

>>> x = Deal.objects.get(id=1)
>>> x.increase_purchases(4)
AttributeError: 'Deal' object has no attribute 'update'

How can I write a proper function to the model so that I can update the selected querys purchases as I want ?

+1  A: 

Modify the appropriate fields then call save() on the instance.

Ignacio Vazquez-Abrams
but as far as I know save will be saving a new instance, while I want to update the existing one. regards
Hellnar
It will only create a new record if the PK is None or does not already exist in the database. Otherwise it will update the existing record with said PK.
Ignacio Vazquez-Abrams
+2  A: 

Based on your example and description, you probably want something like this:

class Deal(models.Model):        
    purchase_count = models.IntegerField(default=0)

    def purchase(self, quantity=1):
       self.purchase_count = self.purchase_count + quantity

I agree with Ignacio; modify the object and then save it. So in the shell:

> great_deal = Deal.objects.get(id=1)
> great_deal.purchase(4)
> great_deal.save()
> # or w/o an explicite argument it will record a single purchase
> # great_deal.purchase()

Yes, I renamed things a little bit in the Deal model. It just seemed more descriptive this way.

istruble
+1  A: 

Or use the += expression for cleaner code:

class Deal(models.Model):        
    purchase_count = models.IntegerField(default=0)

    def purchase(self, quantity=1):
       self.purchase_count += quantity
speakman