首页 > 解决方案 > DRF ForeignKey 值未部分显示

问题描述

我是 python django 的新手,只有几个星期。这是我的第一个问题帖子。

我发现使用 DRF ForeignKey 的问题。外键值(名称)不显示。我有 3 个相互关联的表(品牌、国家、品牌国家)。在遵循了一些教程之后,在 BrandCountry Entity 中,我成功打印出品牌名称(而不是 ID),但它不适用于国家关系的相同代码结构。 国名不显示

我想知道造成这种情况的问题是什么。没有错误或警告消息。我尝试调试,查询运行正确(它正确选择了brand.name 和country.name)。 来自调试的正确查询

我想知道是不是因为:-我使用“代码”作为关系键而不是“ID”?

模型.py

class BrandCountry(models.Model):
    class Meta:
        db_table = 'brand_countries'

    brand = models.ForeignKey(to='brand.Brand', on_delete=models.CASCADE, related_name='ref_brand_country_brand')
    country_code = models.ForeignKey(to='country.Country',
                                    on_delete=models.CASCADE,
                                    related_name='ref_brand_country_country',
                                    max_length=45,
                                    db_column='country_code',
                                    to_field='code')

序列化程序.py

class BrandCountrySerializer(serializers.ModelSerializer):
    brand_name = serializers.StringRelatedField(source='brand.name')
    country_name = serializers.StringRelatedField(source='country.name')

    class Meta:
        model = BrandCountry
        fields = ('id', 'brand_id', 'brand_name', 'country_code', 'country_name')

    @staticmethod
    def setup_eager_loading(queryset):
        queryset = queryset.select_related('brand','country_code')
        return queryset

视图.py

class BrandCountryListView(generics.ListAPIView):
    serializer_class = BrandCountrySerializer
    brand_id = "brand_id"

    def get_queryset(self):
        serializer_class = BrandCountrySerializer.setup_eager_loading(BrandCountry.objects)
        queryset = serializer_class.all()
        brand_id = self.kwargs.get(self.brand_id)
        queryset = queryset.filter(brand_id=brand_id)

        return queryset

我试图在这里和那里调试并找到解决方案几乎花了1天多,但没有结果。如果有人可以帮助我,我真的很感激。抱歉,如果缺少某些内容或不清楚。

标签: pythondjango-rest-frameworkpython-3.6

解决方案


您在序列化程序中使用了错误的引用。country_name所以source='country.name'改为source='country_code.name'

class BrandCountrySerializer(serializers.ModelSerializer):
    brand_name = serializers.StringRelatedField(source='brand.name')
    country_name = serializers.StringRelatedField(source='country_code.name') # Change is here <<<<

    class Meta:
        model = BrandCountry
        fields = ('id', 'brand_id', 'brand_name', 'country_code', 'country_name')

    @staticmethod
    def setup_eager_loading(queryset):
        queryset = queryset.select_related('brand','country_code')
        return queryset



更新
您可以尝试depth属性,如:

class BrandCountrySerializer(serializers.ModelSerializer):
    class Meta:
        model = BrandCountry
        fields = '__all__'
        depth = 1

    @staticmethod
    def setup_eager_loading(queryset):
        queryset = queryset.select_related('brand', 'country_code')
        return queryset

推荐阅读