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

时间:2019-04-09 10:13:47

标签: python django

我有一个名为 Order 的模型,该模型保存了有关用户的信息,还有一个名为 OrderItem 的模型,该模型保存了用户已订购的产品。我已经使用表格内联将OrderItem模型与Order一起加入。现在,我想要的是通过乘以价格和产品数量(这是 OrderItem 模型的字段)来计算总价格,然后将总价格保存在 Order 模型中,如图所示在图片中。
model admin view

我之前曾问过这个问题,但没有得到满意的答复。

from django.contrib import admin
from .models import Order, OrderItem
from pizza_app.models import UserTypes
from django.db.models.signals import pre_save
from django.db.models import Sum, F, FloatField

class OrderItemInline(admin.TabularInline):
    model = OrderItem


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


    def get_form(self, request, obj=None, **kwargs):
        form = super(OrderAdmin,self).get_form(request, obj,**kwargs)
        form.base_fields['Assigned_to'].queryset = form.base_fields['Assigned_to'].queryset.filter(staff_status='Delivery Boy')
        return form

admin.site.register(Order, OrderAdmin)
from django.db import models
from pizza_app.models import MenuVariant
from django.urls import reverse
from django.db.models import Sum, F, FloatField
from pizza_app.models import UserTypes
# from django.contrib.auth.models import User
from django.db.models.signals import pre_save,post_save

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])
    
    total = models.DecimalField(max_digits=10,decimal_places=2,default=0)

    Assigned_to = models.OneToOneField(UserTypes, on_delete=models.CASCADE,default=None, blank=True, null=True)


    class Meta:
        ordering = ('created', )

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


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)
    size = models.CharField(max_length=20, default=None)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    quantity = models.PositiveIntegerField(default=1)


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

1 个答案:

答案 0 :(得分:0)

除了创建模型字段外,还可以在OrderAdmin中创建一个方法以在运行时生成总计。然后在管理员站点中显示它。像这样:

from django.db.models import Sum, F, ExpressionWrapper, DecimalField


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

    def order_total(self, obj):
         return obj.items.annotate(price_per_item=ExpressionWrapper(F('quantity')*F('price'), output_field=DecimalField())).aggregate(sum_total=Sum('price_per_item')).get('sum_total')

total_order的{​​{1}}方法中,我正在使用aggregation计算该订单的总数。然后,我将OrderAdmin添加到total_order中的fieldsreadonly_fields中。