Django Rest Framework如何在不使用SQL外键的情况下序列化多对象

时间:2019-01-02 12:15:07

标签: django serialization django-rest-framework

考虑到sql server的性能,我在设计sql时不使用任何外键,而是使用id引用来联接两个表。但是当我使用Django Rest Framework的序列化序列化多表时,它仅支持外键(对吗?)。

另一个解决方案是使用mysql视图映射到django模型,该模型可以表示多联接表。在这种情况下,我需要将GET和POST方法拆分为两个单独的APIView,而不是泛型。ListCreateAPIView作为一个整体(对于mysql视图模型为GET。对于非myql视图模型为POST),但在静态设计中它们是相同的URI。

GET /school     -- mapping to mysql view for more information
POST /school    -- just create a new host

代码:

class LocationSerializer(model.Model):
    pass

class SchoolSerializer(models.Model):
    pass

class LocationSerializer(serializers.ModelSerializer):
    class Meta:
        model = LocationModel
        fields = ("region", "state", "country")

class SchoolSerializer(serializers.ModelSerializer):
    location = LocationSerializer()
    class Meta:
        model = SchoolModel
        fields = ("name", "level", "location")

class SchoolList(generics.ListCreateAPIView):
    queryset = SchoolModel.objects.all()
    serializer_class = SchoolSerializer

class SchoolDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = SchoolModel.objects.all()
    serializer_class = SchoolSerializer 

0 个答案:

没有答案