[英]Django: Get User profile from User serializer
I have a basic UserProfile
model that has a OneToOne
relationship with a User
model.我有一个基本的
UserProfile
,有一个模型OneToOne
有关系User
模型。
My User serializer works well, though how do I go about retrieving the related UserProfile
model from the same serializer and viewset
?我的 User 序列化程序运行良好,但如何从相同的序列化程序和
viewset
检索相关的UserProfile
模型?
Here is my UserProfile Model:这是我的用户配置文件模型:
class UserProfile(models.Model):
bio = models.CharField(max_length=1000)
cellphone = PhoneNumberField(null=True)
useraccount = models.OneToOneField(User, on_delete=models.CASCADE)
My current viewset:我当前的视图集:
class CurrentUserViewSet(viewsets.ReadOnlyModelViewSet):
serializer_class = CurrentUserSerializer
permission_classes = [IsAuthenticated]
def get_queryset(self):
user = self.request.user
queryset = User.objects.filter(username = user)
return queryset
My User serializer:我的用户序列化程序:
class CurrentUserSerializer(serializers.ModelSerializer):
groups = GroupSerializer(many=True)
class Meta:
model = User
fields = ('username', 'email', 'first_name', 'last_name', 'groups')
def to_representation(self, instance):
return {
'username': instance.username,
'email': instance.email,
'first_name': instance.first_name,
'last_name': instance.last_name,
'groups': GroupSerializer(instance.groups.all(), many=True).data,
}
I attempted the following with my Serializers, but got an attribute error stating that my User model does not have the field profile
:我尝试使用序列化程序执行以下操作,但出现属性错误,指出我的用户模型没有字段
profile
:
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = ('dashboards', 'fullname')
class CurrentUserSerializer(serializers.ModelSerializer):
groups = GroupSerializer(many=True)
profile = TeamMemberDashboardSerializer()
class Meta:
model = User
fields = ('username', 'email', 'first_name', 'last_name', 'groups', 'profile')
def to_representation(self, instance):
return {
'username': instance.username,
'email': instance.email,
'first_name': instance.first_name,
'last_name': instance.last_name,
'groups': GroupSerializer(instance.groups.all(), many=True).data,
'profile': instance.profile
}
Thanks for your time!谢谢你的时间!
The easiest way is to put, for showing profile data is to put depth = 1
in class Meta
of your serializer as follows:最简单的方法是放置,用于显示配置文件数据是将
depth = 1
放入序列化程序的class Meta
中,如下所示:
class CurrentUserSerializer(serializers.ModelSerializer):
groups = GroupSerializer(many=True)
class Meta:
model = User
fields = ('username', 'email', 'first_name', 'last_name', 'groups')
depth = 1
def to_representation(self, instance):
return {
'username': instance.username,
'email': instance.email,
'first_name': instance.first_name,
'last_name': instance.last_name,
'groups': GroupSerializer(instance.groups.all(), many=True).data,
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.