Django inventory app, where to override save for quantity control?

时间:2015-05-18 17:28:29

标签: python django django-admin inventory inventory-management

I have 'three' models:

class Book(models.Model):
    title = models.CharField(max_length=200)
    price = models.FloatField()
    quantity = models.IntegerField()

class Operation(models.Model):
    operation_type_choices = (
        ('sell', 'Sell'),
        ('donation', 'Donation'),
    )
    book = models.ManyToManyField(Book, through = 'BookOperation') 
    operation_type = models.CharField(max_length=50, choices=operation_type_choices)

class BookOperation(models.Model):
    book = models.ForeignKey(Book)
    operation = models.ForeignKey(Operation)
    quantity = models.IntegerField()

I want to know in what model should I override the save() function to manage when a operation is 'sell', so the book.quantity should lower and when it's 'donation' it should rise.

2 个答案:

答案 0 :(得分:0)

我会在您拥有quantity属性的模型中执行此操作。 请查看Signals Documentation以避免覆盖save()方法并使用post_savepre_save方法。

答案 1 :(得分:0)

虽然建模也可以通过其他方式完成,但我认为您选择了对您的要求最有意义的建模。

鉴于具体模型,我认为OperationBookOperation模型在“'操作”时都会被使用。是。这当然取决于您以后如何构建表单以及相对视图。但鉴于此,似乎其中任何一个都足以用于save()函数。

根据它的外观,我肯定使用Book模型,因为这是您的主模型,并且它不会立即受到'操作的影响。事务。