首页 > 解决方案 > 如何在 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)

标签: pythondjango

解决方案


这可以通过为您的类编写自定义模型序列化程序并添加一个通过外键OrderItem指向该字段的字段来完成,如下所示:priceproduct

class OrderItemSerializer(ModelSerializer):
    price = DecimalField(source='product.price')

    class Meta:
        model = OrderItem
        fields = ('price', 'quantity')

如果需要,您只需将模型中的更多字段添加到类的fields属性中Meta。对于该price_per_pound字段,您将创建一个类似的字段,例如price. 最后,您应该配置您的视图集以使用此序列化程序。

如果您要将字段添加到模型类,您将复制数据并将其放在数据库中的 2 个位置。您通常希望避免这种情况。


推荐阅读