我正在尝试使用OneToOneField扩展User模型,因此我可以向用户添加更多字段:
class Userattribs(models.Model):
user = models.OneToOneField(User)
passcode = models.IntegerField(default=0)
# about user
organisation = models.CharField(max_length=100, null=True)
description = models.CharField(max_length=300, null=True)
我还有以下型号序列化器:
class UserattribsSerializer(serializers.ModelSerializer):
class Meta:
model = Userattribs
fields = ('organisation', 'description')
class UserSerializer(serializers.ModelSerializer):
userattribs = UserattribsSerializer(required=True)
class Meta:
model = User
fields =('id', 'username', 'first_name', 'last_name', 'email', 'userattribs')
我遇到的问题是用户序列化,不包括json响应中的'userattribs'。我花了几个小时谷歌搜索和敲打我的头。如果你帮助我,我将永远感激。
提前致谢!
我添加了观点。我注意到的一件奇怪的事情是当我查询(使用UserList)所有数据时,我会得到Userattribs。但是,当我检索单个项目时,我没有得到Userattribs
###################################################
### Views #########################################
###################################################
class UserList(generics.ListCreateAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = (permissions.AllowAny,)
class UserDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = (access_permission,)
答案 0 :(得分:0)
我的代码中没有任何错误。您确定User
个对象有Userattribs
个对象。
使用python manage.py shell
打开你的python shell并输入它来测试你的代码:
#import your related models and serializer
from your_app.models import *
from your_app.serializer import *
# create new user
user = User.objects.create(username="test")
# create new user attrib linked to `user` object
user_attrib = Userattribs.objects.create(user=user, organisation="DJANGO")
# serialize your `user` object
user_serializer = UserSerializer(user)
# display your serialized data
user_serializer.data
# outputs : {'last_name': '', 'userattribs': OrderedDict([('organisation', 'DJANGO'), ('description', None)]), 'email': '', 'username': 'test', 'first_name': '', 'id': 3}
如果没问题,可能会出现问题。