Reputation: 73
I'm new to Django rest and i'm trying to return response that have to use two query sets: The first one is for the specific project and the second one is only for specific users inside this project:
serializers.py
class ProjectFiltersSerializer(serializers.ModelSerializer):
class Meta:
model= Project
fields = ('id', 'title','users')
views.py
class FiltersDetail(APIView):
"""
Retrieve filters instance.
"""
def get_project(self, project_pk):
try:
return models.Project.objects.filter(pk=project_pk)
except Snippet.DoesNotExist:
raise Http404
def get_returning_customers(self, project_pk):
return [(u.pk, u"%s %s" % (u.first_name, u.last_name)) for u in User.objects.filter(return=1)]
def get(self, request, project_pk, format=None):
snippet = self.get_project(project_pk) | self.get_returning_customers(project_pk)
serializer = ProjectFiltersSerializer(snippet, many=True)
return Response(serializer.data)
I'm getting "Cannot combine queries on two different base models". Is this the right way to do this?
Thanks
Upvotes: 0
Views: 137
Reputation: 20102
create a nested serializer (notice it's not a Model Serializer)
class ProjectCustomerSerializer(serializers.Serializer):
users = UserSerializer(many=True)
project = ProjectSerializer()
the UserSerializer and ProjectSerializer can be ModelSerializers however. Then in the view:
def get(....):
serializer = ProjectCustomerSerializer(data={
'users': self.get_returning_customers(project_pk),
'project': self.get_project(project_pk),
})
return Response(serializer.data)
there's another way. You could add a method on the project model (get_returning_customers()) and then add a field on the ProjectSerializer called returning_customers = serializer.ListField(source='get_returning_customers')
Hope this helps
Upvotes: 0
Reputation: 821
You can use Nested Serializer. For more information: http://www.django-rest-framework.org/api-guide/relations/#nested-relationships
Upvotes: 2