如何使用相同模型的其他字段的值在Django模型中创建一个字段?

时间:2019-04-02 10:50:13

标签: python django django-models django-2.1

我想创建一个字段名称: total ,其中包含所有产品的总价格*数量。我想要的是如何在Django模型中进行total = price*quantity。如您所见,可能有不止一种产品。
我通过tabularinline将OderItem模型与Order一起加入。

enter image description here

class OrderItemInline(admin.TabularInline):
    model = OrderItem
    raw_id_fields = ['product']

class OrderAdmin(admin.ModelAdmin):
    list_display = ['id','name', 'mobile_no','address','status', 'created']
    list_editable = ['status']
    list_per_page = 15
    list_filter = ['status']
    search_fields = ('id',)
    inlines = [OrderItemInline]


admin.site.register(Order, OrderAdmin)
class Order(models.Model):
    name = models.CharField(max_length=60)
    email = models.EmailField(max_length=60,default=None, blank=True)
    mobile_no = models.CharField(max_length=13, default=None) 
    address = models.CharField(max_length=150)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    status_choices = (
        ('In Queue', 'In Queue'),
        ('Processing', 'Processing'),
        ('Ready', 'Ready'),
        ('Delivered', 'Delivered'),
        ('Paid', 'Paid'),
        ('Cancelled', 'Cancelled'),
    ) 
    status = models.CharField(max_length=15,       choices=status_choices, default=status_choices[0][0])


    class Meta:
        ordering = ('created', )

    def __str__(self):
        return 'Order {}'.format(self.id)

    def get_total_cost(self):
        return sum(item.get_cost() for item in self.items.all())



class OrderItem(models.Model):
    order = models.ForeignKey(Order, related_name='items', 
    on_delete=models.CASCADE)
    product = models.ForeignKey(MenuVariant, related_name='order_items', 
    on_delete=models.CASCADE, default=None)
    size = models.CharField(max_length=20, default=None)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    quantity = models.PositiveIntegerField(default=1)
    # total = models.DecimalField(max_digits=10, decimal_places=2,default=0)



    def __str__(self):
        return '{}'.format(self.id)

    def get_cost(self):
        return self.price * self.quantity

2 个答案:

答案 0 :(得分:1)

您可以直接通过数据库查询获得Order的总价,因此无需将其保存在数据库中:

from django.db.models import Sum, F, FloatField
orders = Order.objects.annotate(total=Sum(F('items__quantity')*F('items__price'), output_field=FloatField()))

这将向每个查询结果添加一个total字段。然后:

price_of_first_order = orders.first().total

如果您想在管理中显示order的总数,请对ModelAdmin进行子类化,并将get_total_cost添加到readonly_fields中,如{{3}所述。 }:

  

一个只读字段不仅可以显示模型字段中的数据,还可以显示模型方法的输出或ModelAdmin类本身的方法。这与ModelAdmin.list_display的行为非常相似。

答案 1 :(得分:1)

虽然我像dirkgroten一样不太了解将值保存在模型字段中的意义,但您可以在total=models.IntegerField(null=True, blank=True)模型中添加字段Order并使用post_save更新值。

因此,由于您已经拥有get_total_cost(),因此我们可以执行以下操作:

def order_pre_save(sender, instance, **kwargs):
    instance.total_cost = instance.get_total_cost()

pre_save.connect(order_pre_save, sender=Order)

编辑:正如dirkgroten指出的那样,您需要在post_save上使用OrderItem

def order_item_pre_save(sender, instance, **kwargs):
    instance.order.total_cost = instance.order.get_total_cost()
    instance.order.save()

post_save.connect(order_item_pre_save, sender=OrderItem)

您还需要在删除时更新值:

def order_item_pre_delete(sender, instance, **kwargs):
    instance.order.total_cost = instance.order.get_total_cost() - instance.get_cost()
    instance.order.save()

post_delete.connect(order_item_pre_delete, sender=OrderItem)