获取用户Djoser的所有数据

时间:2020-05-01 07:12:00

标签: django djoser

我使用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",

    }
]

1 个答案:

答案 0 :(得分: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"
}

]