如何输出查询结果?

时间:2019-07-15 03:10:04

标签: python django-models

我可以保存项目,但不能查询。

items=PhoneItem.objects.all()
    for item in items:
        print(item)

程序抛出错误:

  

在“用于项中的项:”中引发异常:    init ()接受4个位置参数,但给出了11个

我尝试重新启动程序,但问题仍然存在。

class PhoneItem(models.Model):

     name = models.CharField(max_length=1000)
     phoneNumber = models.CharField(max_length=1000)
     department = models.CharField(max_length=1000)
     namePY = models.CharField(max_length=1000)
     phoneNumberPY = models.CharField(max_length=1000)
     departmentPY = models.CharField(max_length=1000)
     namePinyin = models.CharField(max_length=1000)
     phoneNumberPinyin = models.CharField(max_length=1000)
     departmentPinyin = models.CharField(max_length=1000)
     pass

    def toPY(self,text):
        pinyin=lazy_pinyin(text)
        res=''
        for py in pinyin:
            res=res+py[0]
            pass
        return res

    def toPinyin(self,text):
        pinyin = lazy_pinyin(text)
        res = ''
        for py in pinyin:
            res = res + py
            pass
        return res

    def __init__(self,name,phoneNumber,department):
        super(PhoneItem, self).__init__()
        self.name=name
        self.phoneNumber=phoneNumber
        self.department=department
        self.namePY=self.toPY(name)
        self.phoneNumberPY = self.toPY(phoneNumber)
        self.departmentPY = self.toPY(department)
        self.namePinyin = self.toPinyin(name)
        self.phoneNumberPinyin = self.toPinyin(phoneNumber)
        self.departmentPinyin = self.toPinyin(department)
        pass
    pass

我希望输出所有项目结果。

1 个答案:

答案 0 :(得分:0)

您已经重写了init。但是Django需要在init中获取所有字段,而别无其他:9您的字段,id和self。如果要重写init,则需要编写所有参数。最简单的方法是像这样重写init create factory方法:

class PhoneItem(models.Model):

    @classmethod
    def new(cls,name, phoneNumber, department):
        return ...

或者您可以这样做:

class PhoneItem(models.Model):

   def __init__(self, name, phoneNumber, department, **kwargs):
       super().__init__(name=name, department=department, **kwargs)
       # And everything you need is here