Python 如何使用Django中产品模型的字段填充OrderItem模型?
我使用ModelViewSet和序列化程序查看订单和产品。 所以在我的产品模型的管理面板中,我已经添加了产品、价格和每磅价格。例如(香蕉,2.00,2.99) 在我的OrderItem模型中,我可以选择可用的产品,但当我选择香蕉时,我希望价格和每磅价格字段自动填充我在产品模型中的内容,例如(2.00,2.99)。我该怎么办Python 如何使用Django中产品模型的字段填充OrderItem模型?,python,django,Python,Django,我使用ModelViewSet和序列化程序查看订单和产品。 所以在我的产品模型的管理面板中,我已经添加了产品、价格和每磅价格。例如(香蕉,2.00,2.99) 在我的OrderItem模型中,我可以选择可用的产品,但当我选择香蕉时,我希望价格和每磅价格字段自动填充我在产品模型中的内容,例如(2.00,2.99)。我该怎么办 class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='items
class OrderItem(models.Model):
order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE)
product = models.ForeignKey(Product, related_name='+', on_delete=models.CASCADE)
price = models.DecimalField(Product.price) # Tried this way, but doesn't work.
price_per_pound = models.ForeignKey(Product, related_name='product_price_per_pound', on_delete=models.CASCADE) # this still only give me the field names of my product
quantity = models.PositiveIntegerField(default=1)
ready = 1
on_its_way = 2
delivered = 3
STATUS_CHOICES = (
(ready, 'ready'),
(on_its_way, 'on its way'),
(delivered, 'delivered'),
)
status = models.SmallIntegerField(choices=STATUS_CHOICES)
最好为您的
OrderItem
类编写一个自定义模型序列化程序,并通过外键product
添加一个指向price
字段的字段,如下所示:
class OrderItemSerializer(ModelSerializer):
price = DecimalField(source='product.price')
class Meta:
model = OrderItem
fields = ('price', 'quantity')
如果需要,只需将模型中的更多字段添加到Meta
类的fields
属性中即可。对于price\u per_pound
字段,您可以创建一个类似的字段,如price
。最后,您应该配置视图集以使用此序列化程序
如果将字段添加到模型类中,则会复制数据并将其放在数据库中的两个位置。您通常希望避免这种情况。如果您的产品外键已经包含此信息,为什么要在OrderItem中存储价格和每磅价格?你想做什么?我想在有人试图订购产品时显示“价格”和“每磅价格”字段,使其显示为模型视图。那么糟糕吗?还是不可能?这不是个好主意。最好向OrderItem的modelserializer添加引用产品中字段的额外字段。明白了。谢谢你的帮助。
class OrderItemSerializer(ModelSerializer):
price = DecimalField(source='product.price')
class Meta:
model = OrderItem
fields = ('price', 'quantity')