python - 如何在 django 序列化程序 SlugRelatedField 中获得反向关系
问题描述
我有两个模型 ProductTypeModel 和 ProductModel,product_type 是产品中的外键。然后我为一个产品编写了一个 ModelSerializer 来获取 ProductModel 的所有条目以及一些附加信息。现在我无法从 ProductSerializer 中的 ProductTypeModel 获取 product_sub_type
我在序列化程序中尝试过 SlugRelatedField,尝试设置slug_field=product_sub_type
和slug_field=product_type__product_sub_type
slug_field=product_type.product_sub_type
模型.py
class ProductType(models.Model):
"""Product type model."""
id = models.UUIDField(
primary_key=True,
default=uuid.uuid4,
editable=False
)
hsn = models.ForeignKey(
HSN,
related_name='product_types',
on_delete=models.SET_NULL,
null=True, blank=True
)
product_type = models.CharField(max_length=255, null=True, blank=True)
product_sub_type = models.CharField(max_length=255, db_index=True)
description = models.CharField(max_length=255, null=True, blank=True)
def __str__(self):
return str(self.product_type)
def get_sub_type(self):
return str(self.product_sub_type)
class Meta:
db_table = 'ProductTypes'
unique_together = ('product_type', 'product_sub_type')
class Product(models.Model):
"""Products model."""
product_id = models.UUIDField(
primary_key=True,
default=uuid.uuid4,
editable=False
)
product_type = models.ForeignKey(
ProductType,
related_name='related_products',
on_delete=models.SET_NULL,
blank=True, null=True
)
name = models.CharField(max_length=255, db_index=True)
code_name = models.CharField(max_length=255, null=True, blank=True)
href = models.CharField(max_length=500, blank=True, null=True)
full_name = models.CharField(max_length=255, null=True, blank=True, db_index=True)
manufacturer = models.ForeignKey(
Manufacturer,
related_name='manufactured_products',
on_delete=models.SET_NULL,
null=True, blank=True
)
packing = models.CharField(max_length=255, null=True, blank=True)
packing_detail = models.CharField(max_length=255, null=True, blank=True)
mrp = models.DecimalField(
max_digits=8,
decimal_places=2,
null=True, blank=True
)
created_at = models.DateTimeField(
'created at',
db_index=True,
default=timezone.now
)
def __str__(self):
return str(self.full_name)
class Meta:
db_table = 'Products'
unique_together = ('code_name', 'product_type')
序列化程序.py
class ProductTypeSerializer(serializers.ModelSerializer):
# Serialize/Deserialize ProductType instance.
class Meta:
model = ProductType
fields = (
'id', 'hsn',
'product_type', 'product_sub_type',
'description'
)
read_only_fields = ('id', )
class ProductSerializer(serializers.ModelSerializer):
# Serialize/Deserialize Product instance.
manufacturer = serializers.StringRelatedField()
manufacturer_id = serializers.PrimaryKeyRelatedField(read_only=True)
product_sub_type = serializers.SlugRelatedField(slug_field=????)
class Meta:
model = Product
fields = (
'product_id',
'product_type', 'product_sub_type',
'name', 'code_name',
'manufacturer', 'manufacturer_id',
'full_name',
'packing', 'packing_detail',
'mrp'
)
read_only_fields = (
'product_id', 'created_at',
'product_type', 'manufacturer_id'
)
随之slug_field=product_sub_type
而来
ImproperlyConfigured at /products/
Field name product_sub_type is not valid for model Product.
随之slug_field=product_type.product_sub_type
而来
AttributeError at /products/
Got AttributeError when attempting to get a value for field product_sub_type on serializer ProductSerializer.The serializer field might be named incorrectly and not match any attribute or key on the Product instance.
我希望序列化程序返回如下内容:
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"product_id": "fffcf7ba-5c6d-4190-96d2-cc9125e18e71",
"product_type": "1b3dd955-b67e-4ca3-9561-6d1704ff7c91",
"product_sub_type": "Capsules",
"name": "Enshine Toothpaste",
"code_name": null,
"manufacturer": "Leeford Healthcare Ltd",
"manufacturer_id": 2524,
"full_name": "Enshine Toothpaste",
"packing": null,
"packing_detail": null,
"mrp": null
}
]
}
解决方案
提供属性slug_field
和source
作品为只读的SlugRelatedField
. 要允许在此字段中写入,queryset
还必须提供属性
class ProductSerializer(serializers.ModelSerializer):
...
product_sub_type = serializers.SlugRelatedField(
slug_field='product_sub_type',
source='product_type',
queryset=ProductType.objects.all()
)
根据文档 slug_field
,应该是唯一标识任何给定实例的字段
推荐阅读
- html - 如何为任何正则表达式创建过滤器
- excel - 有没有办法将数字的值更改为VBA中的文本
- c - WDK 模板不会显示在 Visual Studio 2017 中
- common-lisp - Common Lisp 共享结构混淆
- python - Pandas - 带滑动窗口的条件列
- ios - SpriteKit 场景图像在模拟器上显示为红十字
- ms-access - 访问 - 计数/发生查询并返回百分比饼图
- node.js - 是否可以在每帧上以无头 chrome 调用 page.screenshot
- flutter - 如何在 Flutter 中自定义 Steppers 并通过内容中的小部件进行控制?
- c# - AForge:如何制作像 Photoshop 一样的色相/亮度/饱和度效果