在Django Rest Framework视图中映射多个关系

时间:2019-07-15 14:12:04

标签: python django django-models django-rest-framework

在我的DRF中,我想在视图中映射客户/服务关系。 因此,一个客户可以拥有0个服务-

How to join two models in django-rest-framework启发,我的序列化程序类似乎还不错


class CustomerSerializer(serializers.ModelSerializer):

    class Meta:

        model = Customer 
        fields = ['name' , 'phone' ,'email1' ... , 'service_id'] 


class ServiceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Service 
        fields = ['service_name', 'product_name', ...]


class Customer_ServiceSerializer(serializers.ModelSerializer):

    service = ServiceSerializer(many=True, read_only=True)
    class Meta:
        model = Customer
        fields = ['name' , 'phone1' , 'email1' ... 'service']  

我的Customer_ServiceSerializer类似乎正确嵌套了

由于我尝试了多种方法并陷入困境,我陷入了如何在视图中显示这些组合模型的问题


class Customer_serviceListAPIView(generics.ListAPIView):
...

def get(self, request, *args, **kwargs):

以上是我开始发表意见的方式,但我仍然坚持如何解决此问题

例如,尝试了此Serialize multiple models in a single view / https://simpleisbetterthancomplex.com/tips/2016/06/20/django-tip-5-how-to-merge-querysets.html

但是我得到了客户对象,因此无法迭代

预先感谢

修改


class Customer_serviceListAPIView(generics.ListAPIView):
    permission_classes = (IsAuthenticated,)
    queryset = Customer.objects.all()
    serializer_class = Customer_ServiceSerializer
    lookup_field= "name"

需要在视图中做点什么吗?按照目前的样子,它将只显示带有service_id的客户而不是服务详细信息 所以我需要做些额外的事情才能使它像这样

0 个答案:

没有答案