【问题标题】:__init__() takes 1 positional argument but 8 were given__init__() 接受 1 个位置参数,但给出了 8 个
【发布时间】:2020-11-02 18:12:46
【问题描述】:
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() 的方式有问题吗?

【问题讨论】:

    标签: django django-models


    【解决方案1】:

    您需要在__init__ 中使用 argskwargs

    class Transaction(models.Model):    
        
        ...
    
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.set_transaction_id()
    

    您的模型的parent __init__ 方法需要每个模型字段的名称作为位置或关键字参数,当您调用super().__init__() 时,您试图在没有任何参数的情况下调用它。

    【讨论】:

      猜你喜欢
      • 2020-01-30
      • 2015-07-13
      • 2017-04-22
      • 2018-06-21
      • 2014-11-12
      • 2017-11-23
      • 1970-01-01
      相关资源
      最近更新 更多