【发布时间】:2019-09-02 17:43:52
【问题描述】:
我正在尝试覆盖 Django 模型的 save 方法并发送额外的关键字参数。即使代码看起来不错,但我得到了这个错误
raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.name, 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'
【问题讨论】:
-
可以添加完整的错误回溯吗?
-
我刚刚更新了我的帖子.. 请检查
-
您不应将参数
registrtion_no传递给模型类,因为您的模型中未定义registrtion_no字段 -
是否可以使用传递参数即registration_no
标签: django django-rest-framework