python - 编辑序列化程序 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
解决方案
我假设您想将金额乘以产品的价格,将您更新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?
推荐阅读
- python - 如何在不使用 Python 列表的情况下存储用户输入?
- firebase - 将@sys.date_time 值输出到工作表
- reactjs - 容器组件中的访问状态
- python-3.x - 如何在数据框中为每个唯一 ID 执行操作?
- javascript - Express Router Regex - 如何匹配包含连字符的字符串文字?
- php - Imap-open 没有连接到 Gmail - SELinux 问题
- angular - 带有多选表单更改事件的angular6-json-schema-form问题
- php - curl没有下载所有pdf文件PHP
- string - 读取和绘制 2 个列中的经度和纬度数据
- tkinter - 从另一个窗口更新一个窗口的文本小部件