我有以下模型。
class Sale(models.Model):
# a sale can be made by a directSale or an Access
directSale = models.ForeignKey('selling.DirectSale', null=True, blank=True)
access = models.ForeignKey('access.Access', null=True, blank=True)
product = models.ForeignKey(CustomProduct)
price_table = models.ForeignKey('products.CustomPriceTable', related_name='sales', null=True)
quantity = models.PositiveIntegerField(
'quantidade', null=False, blank=False, default=0,
)
discount = models.PositiveSmallIntegerField(
'desconto', null=False, blank=False, default=0,
)
original_price = models.DecimalField(
'preço original', null=False, blank=False, max_digits=10, decimal_places=2, default=0,
)
discount_price = models.DecimalField(
'preço com desconto', null=False, blank=False, max_digits=10, decimal_places=2, default=0,
)
total = models.DecimalField(
'Valor total', null=False, blank=False, default=0, max_digits=10, decimal_places=2
)
created_at = models.DateTimeField(
'Criada em', auto_now_add=True
)
要序列化上面的模型,我有以下序列化程序
class SaleSerializer(serializers.ModelSerializer):
product_pv = serializers.ReadOnlyField(source='product.pv')
product_name = serializers.ReadOnlyField(source='product.name')
product_id = serializers.ReadOnlyField(source='product.id')
direct_sale_date = serializers.ReadOnlyField(source='directSale.date')
client = serializers.ReadOnlyField(source='directSale.client.name')
def __init__(self, direct_sale, *args, **kwargs):
self.direct_sale = direct_sale
super(SaleSerializer, self).__init__(*args, **kwargs)
def create(self, validated_data):
sale = Sale(**validated_data)
sale.directSale = self.direct_sale
price_table = sale.directSale.account.preferences_dict['table_sale']
sale.price_table = sale.product.price_tables.get(name=price_table)
sale.total = sale.calculate_value()
sale.save()
return sale
class Meta:
model = Sale
fields = (
'id',
'access',
'directSale',
'discount',
'discount_price',
'original_price',
'price_table',
'product',
'quantity',
'total',
'direct_sale_date',
'product_pv',
'product_name',
'product_id',
'client',
'created_at'
)
为什么以下代码在字段值中返回None?
from selling.api.serializers import SaleSerializer
from selling.models import Sale
sale = Sale.objects.all()[0]
sale.quantity
1
serializer = SaleSerializer(sale)
serializer.data
ReturnDict([('access', None), ('directSale', None), ('discount', None), ('discount_price', None), ('original_price', None), ('price_table', None), ('product', None), ('quantity', None), ('total', None)])
如上所示,quantity属性的值等于1.但是在'serializer.data'中,quantity属性的值为None。
谢谢!
答案 0 :(得分:0)
在您的SaleSerializer
中,您的第一个参数为direct_sale
,并且您将实例作为direct_sale
的参数传递。
您应该像
一样调用它serializer = SaleSerializer(True, sale)
或
serializer = SaleSerializer(True, instance=sale)