I'm looking to retrieve all employees (User) of the current User (id is given). Employees is a ManyToMany field of User. Currently my query retrieves the current user. And user.employees just returns the ids of all employees.
Would it be possible to make a query to retrieve all the Employees of the current User right away? Or am I just supposed to send more API calls (from the front end) for every user where I retrieve the data of the users by id?
Would be awesome if someone could steer me in the right direction. :)
views.py
# display all your employees
class EmployeeViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
def list(self, request):
queryset = User.objects.filter(pk=request.user.pk) #get current user
serializer = UserSerializer(queryset, many=True)
return Response(serializer.data)
models.py
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
employees = models.ManyToManyField(User, related_name='employees')
serializers.py
class UserSerializer(UserDetailsSerializer):
class Meta(UserDetailsSerializer.Meta):
fields = UserDetailsSerializer.Meta.fields + ('employees')
def update(self, instance, validated_data):
profile_data = validated_data.pop('userprofile', {})
employees = profile_data.get('employees')
instance = super(UserSerializer, self).update(instance, validated_data)
# get and update user profile
profile = instance.userprofile
if profile_data:
if employees:
profile.employees = employees
profile.save()
return instance
rest_auth/serializers.py (dependency)
class UserDetailsSerializer(serializers.ModelSerializer):
"""
User model w/o password
"""
class Meta:
model = UserModel
fields = ('pk', 'username', 'email', 'first_name', 'last_name')
read_only_fields = ('email', )
Example user