我有product serializer
,它返回category_offer_price
和product_offer_price
,在得到这个响应之前,我想比较两个价格,只返回最高的价格。
序列化器.py
class ProductSerializer(ModelSerializer):
category = CategorySerializer()
product_offer_price = SerializerMethodField()
category_offer_price = SerializerMethodField()
class Meta:
model = Products
fields = [
"id",
"product_name",
"slug",
"category",
"description",
"category_offer_price",
"product_offer_price",
"base_price",
"stock",
"is_available",
"created_date",
"images",
"images_two",
"images_three",
]
def get_product_offer_price(self, obj):
try:
product_offer = ProductOffer.objects.get(product=obj)
if product_offer.is_active:
offer_price = product_offer.product_offer_price()
return offer_price
except Exception:
pass
return None
def get_category_offer_price(self, obj):
try:
category_offer = CategoryOffer.objects.get(category=obj.category)
if category_offer.is_active:
offer_price = category_offer.category_offer_price(obj)
return offer_price
except Exception:
pass
return None
型号.py
class Products(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
product_name = models.CharField(max_length=50, unique=True)
slug = models.SlugField(max_length=100, unique=True)
description = models.TextField(max_length=500)
base_price = models.IntegerField()
images = models.ImageField(upload_to="photos/products")
images_two = models.ImageField(upload_to="photos/products")
images_three = models.ImageField(upload_to="photos/products")
stock = models.IntegerField()
is_available = models.BooleanField(default=True)
created_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now=True)
class Meta:
verbose_name_plural = "Products"
def __str__(self):
return self.product_name
我想知道是否可以比较序列化程序类中的序列化程序字段?
3条答案
按热度按时间f1tvaqid1#
您可以覆盖
to_representation()
示例:
mum43rcc2#
你可以使用一个方法来验证你的字段。另外,用get-object-or-404方法替换try:except,用allvalue替换序列化器字段,因为你使用了所有的方法,这样代码就更简洁了。
编辑:正如您所看到的,我在这个解决方案中使用了经典的if/else,尽管从Python3.10开始,您可以使用Match case statement来替换这些条件链。
如果对象不存在:
不过,老实说,如果没有对象,则is_active字段是多余的。
wh6knrhe3#
不确定这是否是您想要的,但您可以使用SerializerMethodField类型的字段,它允许您添加一个计算字段,您可以调用category_offer_higher_price。其值由返回最高值的函数计算。请参见以下链接:https://www.django-rest-framework.org/api-guide/fields/#serializermethodfield