计算字段未保存在 django 管理模型中的数据库中



我在total_amount()方法中重新计算了字段total_amount。这在 django 管理中工作正常,但更新的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定义为property而不是方法。

# 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')

正如@minglyu在他的回答中提到的,如果你可以计算total_amount,你不应该将其保存为数据库字段,因为它引入了数据重复性。

要回答问题 - 如何保存 - 您需要覆盖模型的保存方法,如下所示:

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 save(self, *args, **kwargs):
rate = Product.objects.get(pk=self.order_item.product_id)
self.total_amount = rate.price * self.quantity
super(Orders, self).save(*args, **kwargs)

最新更新