serializers.py:
from django.forms import widgets
from rest_framework import serializers
from .models import Classname, Sectionname, Teachername, Attendancename
from django.contrib.auth.models import User
class UserSerializer(serializers.HyperlinkedModelSerializer):
standard = serializers.PrimaryKeyRelatedField(many=True, queryset=Classname.objects.all())
section = serializers.PrimaryKeyRelatedField(many=True, queryset=Sectionname.objects.all())
teacher = serializers.PrimaryKeyRelatedField(many=True, queryset=Teachername.objects.all())
attend = serializers.PrimaryKeyRelatedField(many=True, queryset=Attendancename.objects.all())
class Meta:
model = User
fields = ('id', 'username', 'standard', 'section', 'teacher', 'attend',)
#when I'm attempting to add 'standard' field it raises above exception.
class ClassSerializer(serializers.ModelSerializer):
class Meta:
model = Classname
fields = ('id', 'class_name',)
class SectionSerializer(serializers.ModelSerializer):
class Meta:
model = Sectionname
fields = ('id', 'class_name', 'section_name')
class TeacherSerializer(serializers.ModelSerializer):
class Meta:
model = Teachername
fields = ('id', 'classname', 'secname', 'teachname')
class AttendanceSerializer(serializers.ModelSerializer):
class Meta:
model = Attendancename
fields = ('id', 'teacher_name', 'date', 'intime', 'outtime')
我的追溯:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/stu/users/
Django Version: 1.8.3
Python Version: 3.4.3
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'student')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware')
Traceback:
File "C:\Users\User\demo\venv\lib\site-packages\django\core\handlers\base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\User\demo\venv\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view
58. return view_func(*args, **kwargs)
File "C:\Users\User\demo\venv\lib\site-packages\django\views\generic\base.py" in view
71. return self.dispatch(request, *args, **kwargs)
File "C:\Users\User\demo\venv\lib\site-packages\rest_framework\views.py" in dispatch
456. response = self.handle_exception(exc)
File "C:\Users\User\demo\venv\lib\site-packages\rest_framework\views.py" in dispatch
453. response = handler(request, *args, **kwargs)
File "C:\Users\User\demo\venv\lib\site-packages\rest_framework\generics.py" in get
199. return self.list(request, *args, **kwargs)
File "C:\Users\User\demo\venv\lib\site-packages\rest_framework\mixins.py" in list
47. return Response(serializer.data)
File "C:\Users\User\demo\venv\lib\site-packages\rest_framework\serializers.py" in data
622. ret = super(ListSerializer, self).data
File "C:\Users\User\demo\venv\lib\site-packages\rest_framework\serializers.py" in data
217. self._data = self.to_representation(self.instance)
File "C:\Users\User\demo\venv\lib\site-packages\rest_framework\serializers.py" in to_representation
572. self.child.to_representation(item) for item in iterable
File "C:\Users\User\demo\venv\lib\site-packages\rest_framework\serializers.py" in <listcomp>
572. self.child.to_representation(item) for item in iterable
File "C:\Users\User\demo\venv\lib\site-packages\rest_framework\serializers.py" in to_representation
430. attribute = field.get_attribute(instance)
File "C:\Users\User\demo\venv\lib\site-packages\rest_framework\relations.py" in get_attribute
367. relationship = get_attribute(instance, self.source_attrs)
File "C:\Users\User\demo\venv\lib\site-packages\rest_framework\fields.py" in get_attribute
71. instance = getattr(instance, attr)
Exception Type: AttributeError at /stu/users/
Exception Value: 'User' object has no attribute 'standard'
我正在关注DRF的教程。我想在'UserSerializer'
中添加与上面所有模型相关的主键参考,但它会引发异常。
由于我有四个模型,所以我在'UserSerializer'
类中采用了四个单独的变量,然后尝试显示用户API。
我做错了吗?请提供你的建议......
提前致谢....
答案 0 :(得分:1)
默认User
模型中没有定义属性standard
。
Django&#39; User
模型中定义的字段为:
您的代码无效,因为standard
模型中未定义User
字段。
您可以扩展User
模型,然后将额外的standard
字段添加到该自定义用户模型。
from django.contrib.auth.models import AbstractUser
from django.db import models
class CustomUser(AbstractUser):
standard = models.CharField() # add the 'standard' field
然后在您的设置中,您需要将其指定为用户模型。
AUTH_USER_MODEL = 'my_app.models.CustomUser'
您可以使用get_user_model()
函数返回当前有效的用户模型,即CustomUser
模型。
答案 1 :(得分:1)
我有同样的问题。在类名模型上创建related_name
时需要提供ForeignKey
,然后在序列化程序上创建反向关系时,应使用related_name
作为变量的名称串行器。例如:
class Classname(models.Model):
user = ForeignKey(User, related_name='standard')
class UserSerializer(serializers.HyperlinkedModelSerializer):
standard = serializers.PrimaryKeyRelatedField(many=True, queryset=Classname.objects.all())
class Meta:
model = User
fields = ('id', 'username', 'standard', 'section', 'teacher', 'attend',)
Here是相关文档。