marcelo.delta
marcelo.delta

Reputation: 3082

How to list all user groups in Django?

I am trying to list users and at the same time with the groups added to each one of them.

How can I do this?

Below is an example I'm trying to do.

Thank you.

Serializer

class serializerUser(serializers.Serializer): 
     id           = serializers.PrimaryKeyRelatedField(read_only=True) 
     first_name   = serializers.CharField() 
     last_name    = serializers.CharField() 
     groups       = serializers.CharField() 
     password     = serializers.CharField(write_only=True) 
     username     = serializers.CharField(write_only=True)

views

class UserList(ListAPIView):
    pagination_class = LimitOffsetPagination
    serializer_class = serializerUser
    queryset = User.objects.all()
    def get_queryset(self):
        users = User.objects.select_related('group').all()
        return users

Error:

django.core.exceptions.FieldError: Invalid field name(s) given in select_related: 'gsroup'. Choices are: (none)

Upvotes: 0

Views: 432

Answers (1)

gmc
gmc

Reputation: 3990

You already got them in user.groups. If you want to show them along with the user, add the groups field to the Meta class fields list, for example:

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = (
            "username",
            "first_name",
            "last_name",
            "email",
            "groups",
        )

Upvotes: 1

Related Questions