2017-08-14 72 views
0

我有以下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

@DanielRoseman是的,我想在管理列表顯示中的訂單數。 –

回答

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') 
+0

在order_count()中,self的值是從哪裏來的? –

+0

添加了模型屬性。它不工作? – itzMEonTV

+0

不,它正在工作,但實際上我想知道它背後的邏輯。 –

相關問題