简体   繁体   中英

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?

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)

Modify serializers.py:

class GroupSerializer(serializers.ModelSerializer):

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM