python - 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天多,但没有结果。如果有人可以帮助我,我真的很感激。抱歉,如果缺少某些内容或不清楚。
解决方案
您在序列化程序中使用了错误的引用。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
推荐阅读
- unity3d - 相机聚焦对象中心
- javascript - 如何为我的 Discord 机器人提供的统计信息创建嵌入(Covid 统计)
- vba - 仅从电子邮件中提取 excel 文档
- c - 通过将第二个字符串的字符一个接一个地复制到第一个字符串的末尾来合并两个字符串
- python - 有返回问题的总和的所有路径
- web-component - 在 Lightning Web 组件中使用 Preact
- javascript - 未处理的拒绝 (TypeError):fs.readdir 不是函数
- https - 为 insecure-requests=redirect 更改 quarkus 安全端口
- c# - 将 .ToArray() 放入 from/in 时,LINQ 查询性能不佳
- amazon-web-services - 是否可以使用“HTTP”协议(而不是 REST)通过 AWS API Gateway 返回 HTML?