Reputation: 3082
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
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