Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

python - drf serializer data not showing all fields data properly

id field and name field not showing in result.

in models.py:

class Group(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=50)
    admin = models.ForeignKey(User, on_delete=models.CASCADE)
    member = models.ManyToManyField(User, related_name='groups_user')

    def __str__(self):
        return self.name

in serializers.py:

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

class GroupSerializer(serializers.Serializer):
    admin = SimpleUserSerializer()
    class Meta:
        model = Group
        fields = ('id','name','admin')

views.py:

@api_view(['GET'])
@permission_classes((IsAuthenticated,))
def getSomeGroup(request):
    allGroup = Group.objects.all().count()
    randomGroupId = random.sample(range(allGroup), 3)
    randomGroup = Group.objects.filter(id__in=randomGroupId)
    serializer = GroupSerializer(randomGroup, many=True)
    #print(serializer)
    return Response(serializer.data)

the result comes like this:

[{"admin":{"id":1,"first_name":"asif","last_name":""}},{"admin":{"id":3,"first_name":"Test2","last_name":"lastname"}},{"admin":{"id":3,"first_name":"Test2","last_name":"lastname"}}]

why id and name field not showing?

question from:https://stackoverflow.com/questions/65931761/drf-serializer-data-not-showing-all-fields-data-properly

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
class SimpleUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'

First try to access all admin

@api_view(['GET'])
@permission_classes(IsAuthenticated)
def getSomeGroup(request):
    randomGroup = Group.objects.all()
    serializer = GroupSerializer(randomGroup, many=True)
    return Response(serializer.data)

If that works there may be issue in your these two line The Issue may be in these two lines

allGroup = Group.objects.all().count()
randomGroupId = random.sample(range(allGroup), 3)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...