首页 > 解决方案 > 计算字段未保存在 django 管理模型的数据库中

问题描述

我重新计算total_amounttotal_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)

标签: pythondjangodjango-modelsdjango-rest-frameworkdjango-admin

解决方案


您不需要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')


推荐阅读