Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用django profileserializer获取用户名_Django_Django Models_Django Rest Framework_Django Views - Fatal编程技术网

使用django profileserializer获取用户名

使用django profileserializer获取用户名,django,django-models,django-rest-framework,django-views,Django,Django Models,Django Rest Framework,Django Views,我用django开发了api。我创建了一个代码结构,如下所示。 如何在类探查器序列化程序中获取用户的名字和姓氏 也就是说,使用ProfileSerializer,我希望获得诸如用户名、姓氏、id号等信息 `` ``只需像这样更改序列化程序 class ProfileSerializer(ModelSerializer): class Meta: model = Profile fields = ('id', 'userKey', 'phone', 'em

我用django开发了api。我创建了一个代码结构,如下所示。 如何在类探查器序列化程序中获取用户的名字和姓氏

也就是说,使用ProfileSerializer,我希望获得诸如用户名、姓氏、id号等信息

``


``只需像这样更改序列化程序

class ProfileSerializer(ModelSerializer):

    class Meta:
        model = Profile
        fields = ('id', 'userKey', 'phone', 'email', 'address', 'userState')

    def to_representation(self, instance):
        data = super().to_representation(instance)
        data.update({'username': instance.userKey.username, 'first_name': instance.userKey.first_name, 'last_name': instance.userKey.last_name})
        return data
简单地定义为


你能展示一下模型吗?一般答案-通过使用或通过使用适当类型字段并设置AttributeSider来更新答案:data.update{'first\u name':instance.userKey.first\u name,'last\u name':instance.userKey.last\u name}AttributeError:'UUID'对象没有属性'first\u name',我得到如下错误。你们能帮我吗?个人资料和用户的关系是什么?
class ProfileSerializer(ModelSerializer):

    class Meta:
        model = Profile
        fields = ('id', 'userKey', 'phone', 'email', 'address', 'userState')

    def to_representation(self, instance):
        data = super().to_representation(instance)
        data.update({'username': instance.userKey.username, 'first_name': instance.userKey.first_name, 'last_name': instance.userKey.last_name})
        return data
class ProfileSerializer(ModelSerializer):
    first_name = serializers.CharField(source='user.first_name', read_only=True)
    last_name = serializers.CharField(source='user.last_name' read_only=True)

    class Meta:
        model = Profile
        fields = ('id', 'userKey', 'phone', 'email',
                  'address', 'userState', 'first_name', 'last_name')