提高TypeError(“%s()得到了意外的关键字参数'%s'”“

时间:2019-04-12 02:07:08

标签: django django-rest-framework

我正在尝试覆盖Django模型的save方法,并发送其他关键字参数。即使代码看起来不错,但我遇到了这个错误

  

提高TypeError(“%s()获得了意外的关键字参数'%s'”%(cls。名称,kwarg))   TypeError:Student()得到了意外的关键字参数“ registration_no”

我的模特:

class StudentManager(models.Manager):
    #check the availability of student
    def CheckRegistration(self, name, registration_no):
        print('inside CHECK REGISTRATION')
        if Student.objects.filter(name=name).exists():
            students = Student.objects.filter(name=name)
            for student in students:

                student_id = student.id
                print(str(student_id))
                registrations = Registration.objects.filter(student=student_id)
                for registration in registrations:
                    print(str(registration))
                    if registration.registration_no==registration_no:
                        raise ValueError('student with same registration number already exist')
                    else:
                        print('registration possible')
                        return 1

class Student(models.Model):
    name = models.CharField(max_length=300)
    sex  = models.CharField(choices=SEX_CHOICES,max_length=255, null=True)
    Category = models.CharField(max_length=100, null=True)
    objects = StudentManager()

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        if(kwargs):
            name = kwargs.get('name')
            registration_no = kwargs.get('registration_no')

            Student.objects.CheckRegistration(name, registration_no)
        super(Student, self).save(*args, **kwargs)

错误回溯

>>>Student.objects.create(name='AA',registrtion_no='BB')
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/tluanga/.local/share/virtualenvs/alpha-back-0LxWEk3n/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/tluanga/.local/share/virtualenvs/alpha-back-0LxWEk3n/lib/python3.6/site-packages/django/db/models/query.py", line 420, in create
    obj = self.model(**kwargs)
  File "/home/tluanga/.local/share/virtualenvs/alpha-back-0LxWEk3n/lib/python3.6/site-packages/django/db/models/base.py", line 501, in __init__
    raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg))
TypeError: Student() got an unexpected keyword argument 'registrtion_no'

1 个答案:

答案 0 :(得分:2)

似乎您在写'registrtion_no'而不是'registration_no'时有错字,请改用此代码:

Student.objects.create(name='AA',registration_no='BB')

希望这会有所帮助!

如果没有,请发布用于“创建”功能的代码