我有以下models.py
from django.db import models
class Customer(models.Model):
Person_Id=models.IntegerField()
Person_Name=models.CharField(max_length=100)
Address=models.CharField(max_length=500)
Email=models.EmailField(null=False, default="")
def __str__(self):
return self.Person_Name
class Items(models.Model):
Item_Code=models.IntegerField()
Item_Name=models.CharField(max_length=200)
def __str__(self):
return self.Item_Name
class Orders(models.Model):
Order_Id=models.ForeignKey(Customer, on_delete=models.CASCADE)
Item_Name=models.ManyToManyField(Items)
Order_date=models.DateField()
Comment=models.CharField(max_length=1000, blank=True)
def __str__(self):
return str(self.Order_Id)
admin.py如下
from django.contrib import admin
from .models import Customer, Orders, Items
class CustomerDetails(admin.ModelAdmin):
list_display = ('Person_Name', 'Address', 'Email','total','count')
readonly_fields = ('total',)
search_fields = ('Person_Name', 'Email')
list_filter = ('Address',)
ordering = ('-Person_Name',)
class OrderDetails(admin.ModelAdmin):
filter_horizontal = ('Item_Name',)
admin.site.register(Customer, CustomerDetails)
admin.site.register(Items)
admin.site.register(Orders, OrderDetails)
现在,我想知道每个客户下了多少订单。我知道可以使用反向查找外键,但我没有采用正确的方法。
答案 0 :(得分:0)
你可以做到
class Customer(models.Model):
Person_Id=models.IntegerField()
Person_Name=models.CharField(max_length=100)
Address=models.CharField(max_length=500)
Email=models.EmailField(null=False, default="")
def __str__(self):
return self.Person_Name
@property
def order_count(self):
return Orders.objects.filter(Order_Id=self).count() # or self.orders_set.all().count()
和
class CustomerDetails(admin.ModelAdmin):
list_display = ('Person_Name', 'Address', 'Email', 'order_count')