How to get the nested objects in DRF

I have two models Role and User. User model has a foreign-key field associated with model Role.

Model Role

class Role(models.Model):
    
    role_name = models.CharField(max_length=255, blank=False, unique=True)

    def __str__(self):

        return 'Role Object ({})'.format(self.id, self.role_name)

Model User

class User(AbstractBaseUser, PermissionsMixin):
    
    first_name = models.CharField(max_length=255, blank=False)
    last_name = models.CharField(max_length=255, blank=False)
    email = models.EmailField(max_length=255, blank=False, unique= True)
    phone_number = models.BigIntegerField(blank=False, unique= True)
    password = models.TextField(blank=False)
    company_name = models.CharField(max_length=255, null=True, unique=True)
    is_active = models.BooleanField(default= False)
    role = models.ForeignKey(Role, related_name='group_name', on_delete=models.CASCADE, blank=False)
    business = models.ForeignKey(Businesses, on_delete=models.CASCADE, null=True)

    objects = UserManager()

    USERNAME_FIELD = 'email'

    def __str__(self):

        return 'User Object ({})'.format(self.id)

Using ModelSerializer and ListAPIView I want to get the list of all the users as shown below –

{
    "first_name": "",
    "last_name":"",
    "email":"",
    "phone_number":,
    "is_active":"",
    "role":{
            "id":1,
            "role_name": "Admin"
           }
}

Also, I have created serializers –

class AdminSerializer(serializers.ModelSerializer):

    role = RoleSerializer(read_only=True)

    class Meta:
        model = User
        fields = ['id', 'first_name', 'last_name', 'email', 'phone_number', 'password', 'role', 'is_active' ]
        read_only_field = ['role_name']
        extra_kwargs = {
            'password':{
                'write_only':True
            },
            'is_active':{
                'required':False
            }
        }

    def create(self, validated_data):

        return User.objects.create_user(**validated_data)


class RoleSerializer(serializers.ModelSerializer):

    class Meta:
        model = Role
        field = ['id', 'role_name']

What exactly should I do to my serializer to achieve desire output. What exactly should I write in my ListAPIView() what a ListAPIVIew returns.

class UsersListAPIView(ListAPIView):

    def get(self, request, format=None):

        serializer_class = AdminSerializer

        def get_queryset(self):

            return User.objects.filter(role=request.query_param.get['id']).prefetch_related("group_name")
        
        return Response (self.get_queryset())

This returns an error –

AssertionError: 'UsersListAPIView' should either include a `queryset` attribute, or override the `get_queryset()` method.

Go to Source
Author: Jeet Patel