首页 > 解决方案 > 编辑序列化程序 Django Rest 中的属性值

问题描述

我要做的是更改序列化程序中属性的值(似乎是更改它的适当位置)。

"unsupported operand type(s) for *: 'int' and 'DeferredAttribute'".

这是我按照自己的方式做的时候收到的错误。任何援助都将受到欢迎。

楷模:

class Product(models.Model):
    price =models.IntegerField
    name=models.CharField(null=True)

在另一个应用程序中,我有另一个模型

class Order_unit(models.Model):
    amount=models.IntegerField
    price=models.IntegerField
    product=models.ForeignKey(Product)

序列化器:

from order.models import *
from product.models import *

class OrderUnitSerializer(serializers.ModelSerializer):
    price= serializers.SerializerMethodField('get_price')
    class Meta:
        model = Order_unit
        fields = ['order', 'product', 'amount', 'price']

    def get_price(self,Order_unit):
        price= Order_unit.amount*Product.price
        return price
    
  

标签: pythondjangodjango-rest-framework

解决方案


我假设您想将金额乘以产品的价格,将您更新get_price为:

def get_price(self,order_unit):
    return order_unit.amount * order_unit.product.price # access the price of the product associated with the order_unit object

我也注意到你import *不推荐使用哪个,看看这个问题Why is "import *" bad?


推荐阅读