使用 prefetch_related 的 DRF

DRF using prefetch_related

我有两个 类 容器和组件,每个容器都有几个组件。 我只想在一个查询中获取所有容器及其所有相关组件,我认为 prefretch_related 可以做到这一点,但在 api 的 DRF 中,我只收到没有相关组件的容器

models.py

class Vessel(models.Model):
    name = models.CharField(max_length=255, null=True, blank=True)
    imo = models.CharField(max_length=255, null=True, blank=True)

    def __str__(self):
        return self.name

class Component(models.Model):
    vessel = models.ForeignKey(
        Vessel, blank=True, null=True, on_delete=models.CASCADE, related_name='vessel_components')
    name = models.CharField(max_length=200, blank=True, null=True)
    manufacturer = models.CharField(max_length=200, blank=True, null=True)
    model = models.CharField(max_length=200, blank=True, null=True)
    type = models.CharField(max_length=200, blank=True, null=True)
    remarks = models.TextField(blank=True, null=True)

    def __str__(self):
        return self.name

serializers.py

class VesselSerializer(serializers.ModelSerializer):
    class Meta:
        model = Vessel
        fields = '__all__'
class ComponentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Component
        fields = '__all__'

观点:

@api_view(['GET'])
def getVessels(request):
    vessels = Vessel.objects.all().prefetch_related('vessel_components')
    vSerializer = VesselSerializer(vessels, many=True)
    return Response(vSerializer.data)

我得到的结果:

I thought prefretch_related does that trick but in DRF.

这将为 Vessel 获取 Component,但由于您的序列化程序不会序列化这些组件,因此它们不会出现在结果中。

您应该将 ComponentSerializer 定义为 VesselSerializer 的子序列化器,因此:

class ComponentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Component
        fields = '__all__'

class VesselSerializer(serializers.ModelSerializer):
    <strong>vessel_components = ComponentSerializer(many=True)</strong>  # 🖘 subserializer
    
    class Meta:
        model = Vessel
        fields = '__all__'