0

我使用 userProfile 模型下面的代码。它具有 djoser auth_user 的“OneToOneField”。我想为用户凝胶所有数据。

from django.db import models
from django.contrib.auth.models import User

class userProfile(models.Model):

    user=models.OneToOneField(User,on_delete=models.CASCADE,related_name="profile")
    date_joined=models.DateTimeField(auto_now_add=True)
    updated_on=models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.user.username

和seralizers类显示在下面;

from rest_framework import serializers
from .models import userProfile
class userProfileSerializer(serializers.ModelSerializer):
    user=serializers.StringRelatedField(read_only=True)
    class Meta:
        model=userProfile
        fields='__all__'

我想让所有用户使用 ;

class userAccountsListView(ListAPIView):

    queryset=userProfile.objects.all()
    serializer_class=userProfileSerializer

它返回类似的数据;

[
    {
        "id": 1,
        "date_joined": "2020-04-16T16:50:38.218964+03:00",
        "updated_on": "2020-04-16T16:50:38.218996+03:00",
        "user": 5
    },
    {
        "id": 2,
        "date_joined": "2020-04-30T13:53:48.859116+03:00",
        "updated_on": "2020-04-30T13:53:48.859149+03:00",
        "user": 6
    }
]

我想获取所有用户信息;

[
    {
        "id": 1,
        "date_joined": "2020-04-16T16:50:38.218964+03:00",
        "updated_on": "2020-04-16T16:50:38.218996+03:00",
        "user": 5,
        "first_name": "xxxxx",
        "last_name": "xxxxx",
        "email":"xxxx",
    },
    {
        "id": 2,
        "date_joined": "2020-04-30T13:53:48.859116+03:00",
        "updated_on": "2020-04-30T13:53:48.859149+03:00",
        "user": 6,
        "first_name": "xxxxx",
        "last_name": "xxxxx",
        "email":"xxxx",

    }
]
4

1 回答 1

0

我添加了自己的 CurrentUserSerializer。

class CurrentUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('username', 'email', 'id','first_name','last_name')

class userProfileSerializer(serializers.ModelSerializer):
    user=CurrentUserSerializer(read_only=True)
    class Meta:
        model=userProfile
        fields='__all__

我得到 json 输出;

[
{
    "id": 1,
    "user": {
        "username": "x",
        "email": "x",
        "id": 5,
        "first_name": "x",
        "last_name": "x"
    },
    "date_joined": "2020-04-16T16:50:38.218964+03:00",
    "updated_on": "2020-04-16T16:50:38.218996+03:00"
},
{
    "id": 2,
    "user": {
        "username": "x",
        "email": "x",
        "id": 6,
        "first_name": "x",
        "last_name": "x"
    },
    "date_joined": "2020-04-30T13:53:48.859116+03:00",
    "updated_on": "2020-04-30T13:53:48.859149+03:00"
}

]

于 2020-05-01T10:43:08.457 回答