我需要显示与相同模型有多对多关系的相关字段。 Django Rest Frame工作
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了我需要显示与相同模型有多对多关系的相关字段。 Django Rest Frame工作相关的知识,希望对你有一定的参考价值。
我正在尝试创建一个相关的产品领域,我已经在模型中添加了多对多关系并将其设置为自我,因为我将手动选择相关产品。
class ProductsSerializer(serializers.ModelSerializer):
images = ImagesSerializer(many=True)
color = ColorSerializer(many=False)
class Meta:
fields = (
'url',
'id',
"code",
"sku",
"title",
"slug",
"state",
"old_price",
"price",
"valid",
"in_stock",
"category",
"related_products",
"color",
"images",
"video",
"description",
"fabric",
"model_size_info",
)
model = Products
我不能引用相同的Serializer我需要在api json中获取产品详细信息。我找不到办法做到这一点。
感谢您提前帮助。
答案
方法-1:覆盖__init__()
方法
class ProductsSerializer_Temp(serializers.ModelSerializer):
images = ImagesSerializer(many=True)
class Meta:
fields = (
'url',
'id',
"title",
"images",
)
model = Products
class ProductsSerializer(ProductsSerializer_Temp):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields.update(
{"related_products": ProductsSerializer_Temp()}
)
另一答案
首先,我认为你应该使用像DynamicFieldsModelSerializer这样的东西来防止递归
class DynamicFieldsModelSerializer(serializers.ModelSerializer):
"""
A ModelSerializer that takes an additional `fields` argument that
controls which fields should be displayed.
"""
def __init__(self, *args, **kwargs):
# Don't pass the 'fields' arg up to the superclass
fields = kwargs.pop('fields', None)
# Instantiate the superclass normally
super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)
if fields is not None:
# Drop any fields that are not specified in the `fields` argument.
allowed = set(fields)
existing = set(self.fields)
for field_name in existing - allowed:
self.fields.pop(field_name)
然后,您可以使用SerializerMethodField
并在相关产品中指定您想要的字段('不要通过related_products
以防止递归'):
class ProductsSerializer(DynamicFieldsModelSerializer):
images = ImagesSerializer(many=True)
related_products = serializers.SerializerMethodField()
def get_related_products(self, obj):
return ProductsSerializer(obj.related_products, many=True, fields=('url', 'id', "title", "images")).data
class Meta:
fields = (
'url',
'id',
"title",
"related_products",
"images",
)
model = Products
另一答案
这是我遇到过的解决方案。我创建了另一个Serializer
class ProductsSerializerTemp(serializers.ModelSerializer):
color = ColorSerializer(many=False)
class Meta:
fields = (
"color",
"url"
)
model = Products
而且我把它推荐给我原来的Serializer
class ProductsSerializer(serializers.ModelSerializer):
images = ImagesSerializer(many=True)
color = ColorSerializer(many=False)
related_products = ProductsSerializerTemp(many=True)
class Meta:
fields = (
'url',
'id',
"code",
"sku",
"title",
"slug",
"state",
"old_price",
"price",
"valid",
"in_stock",
"category",
"related_products",
"color",
"images",
"video",
"description",
"fabric",
"model_size_info",
)
model = Products
我几乎完成了这项工作,我不确定这是否是最好的解决方案,但效果非常好。
以上是关于我需要显示与相同模型有多对多关系的相关字段。 Django Rest Frame工作的主要内容,如果未能解决你的问题,请参考以下文章