考虑到模型
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()
函数,通过对Book的模型执行movement()
函数来更改图书数量(至少这是我的意图)。
决定存货数量应该加还是减的逻辑在这个函数中,这是正确的方法吗
另外,我知道我的代码在Python如何处理对象方面是非常错误的,当我在管理面板上保存一个操作时,我得到了movment() takes exactly 2 arguments (3 given)
,为什么?我好像只经过op.operation_type, bok_op.quantity
谢谢你的帮助
我不太清楚为什么要重写
save
,但是应该将super
调用设置为最后一个,因为这是实际保存实例数据的原因Re“只接受2个参数(给定3个)”,
Book
类中的movement
方法的定义应将self
作为其第一个参数。所有Python方法调用都自动作为第一个方法参数传递给实例本身有关更多信息,请参阅Python文档:"the method function is declared with an explicit first argument representing the object, which is provided implicitly by the call..."
(另外,您没有告诉我们
liv
是在哪里定义的,因此我们无法通过阅读您的代码来确定它是什么,似乎应该是self
)相关问题 更多 >
编程相关推荐