Python Django多对多存储的正确方法
考虑到模型Python Django多对多存储的正确方法,python,django,Python,Django,考虑到模型 class Book(models.Model): title = models.CharField(max_length=200) price = models.FloatField() inventory_quantity = models.IntegerField() def movement(type, qty): # ... if type == 'sell': self.inventory_quantit
class Book(models.Model):
title = models.CharField(max_length=200)
price = models.FloatField()
inventory_quantity = models.IntegerField()
def movement(type, qty):
# ...
if type == 'sell':
self.inventory_quantity -= qty
if type == 'donation':
self.inventory_quantity += qty
# ...
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)
def save(self, *args, **kwargs):
super(Operation, self).save(*args,**kwargs)
bok_op = BookOperation()
bok = Book()
op = Operation()
bok.movement(op.operation_type, bok_op.quantity)
class BookOperation(models.Model):
book = models.ForeignKey(Book)
operation = models.ForeignKey(Operation)
quantity = models.IntegerField()
在操作模型上,我重写了save()
函数,通过在图书模型上执行movement()
函数来更改图书数量(至少这是我的意图)。
确定库存数量应加或减的逻辑在此函数中,这是正确的方法吗
另外,我知道我的代码在Python如何处理对象方面是非常错误的,当我在管理面板上保存一个操作时,我得到的movint()正好有2个参数(给定3个)
,为什么?似乎我只传递了op.operation\u type,bok\u op.quantity
感谢您的帮助我不太清楚您为什么要覆盖
保存
,但您应该在那里最后调用超级
,因为这是实际保存实例数据的原因
Re“正好取2个参数(3个给定)”,类中移动
方法的定义应以self
作为其第一个参数。所有Python方法调用都自动作为第一个方法参数传递给实例本身
有关更多信息,请参阅Python文档:
(另外,你没有告诉我们liv
是在哪里定义的,所以我们无法确定它是什么——从阅读你的代码来看,它应该是self
。。movement(type,qty)
应该是。movement(self,type,qty)
,因为它是一个实例方法