class Transaction(models.Model):
slug = models.SlugField(max_length=200, db_index=True)
order_type = models.CharField(verbose_name="Order Method", max_length=200, choices=ORDER_METHODS)
paid = models.BooleanField(verbose_name="Paid", default=False)
closed = models.BooleanField(verbose_name="Closed", default=False)
created = models.DateTimeField(verbose_name="Date of creation", auto_now_add=True)
id_num = models.IntegerField(verbose_name="Transaction ID", db_index=True)
def __init__(self):
super().__init__()
self.set_transaction_id()
def set_transaction_id(self):
self.id_num = int(str(self.created.year) + str(self.created.month) + str(self.created.day).zfill(2) +\
str(self.created.hour) + str(self.created.minute).zfill(2) + str(self.created.second).zfill(2))
当我在这样的视图中创建此模型时:
transaction = Transaction(order_type='Choice_1',
paid=False, closed=False)
transaction.save()
我收到此错误__init__() takes 1 positional argument but 8 were given
。
方法set_transaction_id()
使用日期和时间来设置id_num
。
我声明__init__
并使用super()
或调用set_transaction_id()
的方式有问题吗?
答案 0 :(得分:1)
您需要在args
中使用 kwargs
和 __init__
:
class Transaction(models.Model):
...
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.set_transaction_id()
模型的 parent __init__
方法期望每个模型字段的名称作为位置或关键字参数,并且当您调用super().__init__()
时,您正在尝试调用它没有任何参数。