You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将OrderItem模型的unit_price字段与Photograph模型price字段同步?

实现OrderItem的unit_price与Photograph的price同步显示

你需要让OrderItem模型的unit_price和关联的Photograph模型的price保持一致,这里提供两种可行方案:

方案一:动态获取最新价格(推荐,无需存储字段)

如果不需要把unit_price存在数据库,只是显示时和Photograph的price一致,直接把unit_price改成模型的属性方法,每次访问都会自动取关联商品的最新价格:

修改后的OrderItem模型代码:

from decimal import Decimal
from django.core.validators import MinValueValidator
from django.db import models

class OrderItem(models.Model):
    order = models.ForeignKey(
        Order, on_delete=models.PROTECT, null=True, blank=True)
    product = models.ForeignKey(
        Photograph, on_delete=models.PROTECT, null=True, blank=True)
    quantity = models.PositiveBigIntegerField(default=0, null=True, blank=True)
    # 移除原有的unit_price数据库字段
    order_added = models.DateTimeField(auto_now_add=True)

    @property
    def unit_price(self):
        # 关联商品存在时返回其price,否则返回默认值0.00
        return self.product.price if self.product else Decimal('0.00')

    def __str__(self):
        return f'ID: {self.order.id}' if self.order else '未关联订单'

之后不管在模板里用{{ order_item.unit_price }},还是代码里调用order_item.unit_price,都会拿到对应Photograph的最新价格,完全同步。

方案二:保存时同步价格(需存储字段)

如果必须在数据库中保留unit_price字段,就重写OrderItem的save方法,在保存时自动把值设为关联商品的price:

修改后的OrderItem模型代码:

from decimal import Decimal
from django.core.validators import MinValueValidator
from django.db import models

class OrderItem(models.Model):
    order = models.ForeignKey(
        Order, on_delete=models.PROTECT, null=True, blank=True)
    product = models.ForeignKey(
        Photograph, on_delete=models.PROTECT, null=True, blank=True)
    quantity = models.PositiveBigIntegerField(default=0, null=True, blank=True)
    unit_price = models.DecimalField(max_digits=6, 
                                decimal_places=2,
                                validators=[MinValueValidator(1)]
                                )
    order_added = models.DateTimeField(auto_now_add=True)

    def save(self, *args, **kwargs):
        # 关联商品存在时,自动同步unit_price
        if self.product:
            self.unit_price = self.product.price
        # 调用父类的save方法完成保存
        super().save(*args, **kwargs)

    def __str__(self):
        return f'ID: {self.order.id}' if self.order else '未关联订单'

这样每次创建或修改OrderItem并保存时,unit_price都会自动和关联Photograph的price保持一致。但要注意:如果之后Photograph的price更新了,已经保存的OrderItem的unit_price不会自动跟着变,需要手动写脚本或用Django信号来批量更新。


内容的提问来源于stack exchange,提问作者David Henson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 01:05:38