python - 计算字段未保存在 django 管理模型的数据库中
问题描述
我重新计算total_amount
了total_amount()
方法中的字段。这在 django admin 中工作正常,但更新的值total_amount
没有保存在数据库列中。
这是我的models.py
class Orders(models.Model):
order_id = models.IntegerField(primary_key=True)
order_item = models.ForeignKey('Product', models.DO_NOTHING, db_column='order_item', blank=True, null=True,
related_name='ordered_item')
order_status = models.CharField(max_length=100, blank=True, null=True)
delivery_address = models.TextField(blank=True, null=True)
customer = models.ForeignKey('User', models.DO_NOTHING, db_column='customer', blank=True, null=True)
quantity = models.IntegerField()
rate = models.ForeignKey('Product', models.DO_NOTHING, db_column='rate', blank=True, null=True)
total_amount = models.DecimalField(blank=True, null=True,decimal_places=2,max_digits=10)
def total_amount(self):
rate = Product.objects.get(pk=self.order_item.product_id)
self.total_amount = rate.price * self.quantity
return self.total_amount
class Meta:
managed = False
db_table = 'orders'
我从total_amount()
方法中获得的值没有在数据库中更新。
这是我的 admin.py
class OrderAdmin(admin.ModelAdmin):
list_display = ('order_id', 'order_item', 'order_status', 'delivery_address', 'customer',
'quantity','unit_rate','total_amount')
exclude = ['rate']
readonly_fields = ('unit_rate','total_amount',)
def unit_rate(self,obj):
rate = Product.objects.get(pk=obj.order_item.product_id)
return rate.price
admin.site.register(Orders,OrderAdmin)
解决方案
您不需要total_amount
作为模型字段,因为它可以从其他字段派生,而且最好定义total_amount
为 aproperty
而不是方法。
# models.py
class Orders(models.Model):
order_id = models.IntegerField(primary_key=True)
...
# total_amount = models.DecimalField(blank=True, null=True,decimal_places=2,max_digits=10)
@property
def total_amount(self):
...
# admin.py
list_display = (..., 'total_amount')
推荐阅读
- session - 如何处理同一用户的多个会话
- google-kubernetes-engine - 检查 GKE 集群中的 PoDSecurityPolicy 状态
- r - 以对数刻度显示范围
- python - 如何在python中计算表面的不规则性
- spring-mvc - 类“javax.annotation.Nullable”的签名者信息与其他类的签名者信息不匹配
- android - 是否可以通过 Intent 在活动之间传递 URL?
- reactjs - ReactJS CoreUI - 如何在侧边栏项中使用 URL 路径参数
- azure-devops - 如何备份 Azure Devops 上的数据?
- mysql - 查询生成器返回不正确的日期时间比较查询结果
- openedge - 如何逃避更新消息?