python - 如何在 Django 中使用我的 Product 模型中的字段填充我的 OrderItem 模型?
问题描述
我正在使用 ModelViewSet 和序列化程序来查看我的订单和产品。因此,在我的产品模型的管理面板中,我已经添加了产品、价格和每磅价格。所以例如。(香蕉,2.00,2.99)。
class Product(models.Model):
name = models.CharField(max_length=70)
price = models.DecimalField(max_digits=10, decimal_places=2)
price_per_pound = models.DecimalField(max_digits=10, decimal_places=2, default=0.00)
category = models.ForeignKey(Categories, related_name='products', on_delete=models.CASCADE)
def __str__(self):
return self.name
在我的 OrderItem 模型中,我可以选择可用的产品,但是当我选择香蕉时,我希望 price 和 price_per_pound 字段自动填充我在 Product 模型中的内容,例如(2.00、2.99)。我该怎么办?
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
指向该字段的字段来完成,如下所示:price
product
class OrderItemSerializer(ModelSerializer):
price = DecimalField(source='product.price')
class Meta:
model = OrderItem
fields = ('price', 'quantity')
如果需要,您只需将模型中的更多字段添加到类的fields
属性中Meta
。对于该price_per_pound
字段,您将创建一个类似的字段,例如price
. 最后,您应该配置您的视图集以使用此序列化程序。
如果您要将字段添加到模型类,您将复制数据并将其放在数据库中的 2 个位置。您通常希望避免这种情况。
推荐阅读
- graphql - 如何在 nuxt/apollo 中传递动态令牌?
- deployment - Microsoft.AspNetCore.App vs Microsoft.NETCore.App 发布问题
- android - 更新后如何在最新的 Firebase 存储中上传和检索图像
- python - 不确定为什么合并时出现关键错误
- spring - 找不到 postgresql jdbc 驱动程序
- android - ImageView android:cropToPadding,它实际上是做什么的?
- chisel - 在测试仪中使用多个时钟
- excel - 对于范围内的每个单元格,总计下一列单元格
- css - R DT 覆盖默认选择颜色
- api - Alexa Proactive Events API - 如何确定用户是否禁用了 Alexa 通知?