如何在DRF商品详情接口的关联商品中展示优惠相关字段
解决方案
方法一:扩展关联商品序列化器,添加所需字段
直接修改RelatedProductSerializer,把商品详情序列化器里的三个优惠相关字段加上,同时复用你原本在ProductDetailserializer中的取值逻辑:
class RelatedProductSerializer(ModelSerializer): product_offer_discount = SerializerMethodField() category_offer_discount = SerializerMethodField() highest_offer_price = SerializerMethodField() class Meta: model = Products fields = [ 'product_name', 'slug', 'base_price', 'images', 'highest_offer_price', 'product_offer_discount', 'category_offer_discount' ] # 复制你在ProductDetailserializer中对应的三个get方法实现 def get_product_offer_discount(self, obj): return obj.product_offer.discount_percentage if obj.product_offer else 0 def get_category_offer_discount(self, obj): return obj.category.category_offer.discount_percentage if obj.category.category_offer else 0 def get_highest_offer_price(self, obj): product_discount = obj.product_offer.discount_percentage if obj.product_offer else 0 category_discount = obj.category.category_offer.discount_percentage if obj.category.category_offer else 0 max_discount = max(product_discount, category_discount) return obj.base_price * (1 - max_discount / 100) if max_discount > 0 else obj.base_price
修改完成后,ProductDetailserializer里的get_related_products方法无需改动,关联商品返回的数据就会包含这三个字段。
方法二:复用商品详情序列化器,过滤返回字段
如果不想重复编写方法逻辑,可以直接用ProductDetailserializer序列化关联商品,再手动筛选出需要的字段:
修改ProductDetailserializer中的get_related_products方法:
def get_related_products(self, obj): products = Products.objects.filter(category=obj.category).exclude(id=obj.id) # 用详情序列化器处理关联商品 serializer = ProductDetailserializer(products, many=True, context=self.context) # 筛选出需要的字段 filtered_products = [] for item in serializer.data: filtered_products.append({ 'product_name': item['product_name'], 'slug': item['slug'], 'base_price': item['base_price'], 'images': item['images'], 'highest_offer_price': item['highest_offer_price'], 'product_offer_discount': item['product_offer_discount'], 'category_offer_discount': item['category_offer_discount'] }) return filtered_products
这种方式无需新增序列化器,直接复用已有逻辑,适合快速实现需求。
修改后预期响应示例
关联商品部分会变成:
"related_products": [ { "product_name": "Pendant 2", "slug": "pendant-2", "base_price": 3500, "images": "http://127.0.0.1:8000/media/photos/products/pendant2.webp", "highest_offer_price": 3150, "product_offer_discount": 10, "category_offer_discount": 5 } ]
内容的提问来源于stack exchange,提问作者Sins97
相关产品推荐
相关产品推荐

