2013-08-07 205 views
45
class PurchaseOrder(models.Model): 
    product = models.ManyToManyField('Product') 
    vendor = models.ForeignKey('VendorProfile') 
    dollar_amount = models.FloatField(verbose_name='Price') 


class Product(models.Model): 
    products = models.CharField(max_length=256) 

    def __unicode__(self): 
     return self.products 

我有那個代碼。不幸的是,錯誤出現在admin.py與ManyToManyField多對多的列表顯示django

class PurchaseOrderAdmin(admin.ModelAdmin): 
    fields = ['product', 'dollar_amount'] 
    list_display = ('product', 'vendor') 

錯誤說:

'PurchaseOrderAdmin.list_display [0]', '產品' 是一個ManyToManyField 不被支持。

然而,當我把'product'list_display它編譯。那麼如何在list_display中顯示'product'而不會給出錯誤?

編輯:也許一個更好的問題將是如何顯示ManyToManyFieldlist_display

回答

96

您可能無法直接進行此操作。 From the documentation of list_display

ManyToManyField字段不支持,因爲這將意味着 執行單獨的SQL語句,爲表中的每一行。如果 想要執行此操作,請爲模型提供一種自定義方法,並將該方法的名稱添加到list_display的 。 (請閱讀下面的list_display更多的自定義 方法。)

你可以做這樣的事情:

class PurchaseOrderAdmin(admin.ModelAdmin): 
    fields = ['product', 'dollar_amount'] 
    list_display = ('get_products', 'vendor') 

    def get_products(self, obj): 
     return "\n".join([p.products for p in obj.product.all()]) 

或定義模型的方法,並使用該

class PurchaseOrder(models.Model): 
    product = models.ManyToManyField('Product') 
    vendor = models.ForeignKey('VendorProfile') 
    dollar_amount = models.FloatField(verbose_name='Price') 

    def get_products(self): 
     return "\n".join([p.products for p in self.product.all()]) 

和在管理員list_display

list_display = ('get_products', 'vendor') 
+0

這看起來像一個很好的解決方案。謝謝。雖然,我現在得到一個錯誤,說「列中的空值」product_id「違反非空約束 」任何想法這是什麼意思? – Mdjon26

+0

這可能是一個數據問題。檢查數據庫中的值 – karthikr

+1

由於這會使數據庫癱瘓,因此如何通過select_related()或prefetch_related()來提高性能? – gorus

7

這樣,您就可以做到這一點,請簽出下面的代碼片段:

class Categories(models.Model): 
    """ Base category model class """ 

    title  = models.CharField(max_length=100) 
    description = models.TextField() 
    parent  = models.ManyToManyField('self', default=None, blank=True) 
    when  = models.DateTimeField('date created', auto_now_add=True) 

    def get_parents(self): 
     return ",".join([str(p) for p in self.parent.all()]) 

    def __unicode__(self): 
     return "{0}".format(self.title) 

而在你的admin.py模塊調用方法如下:

class categories(admin.ModelAdmin): 
    list_display = ('title', 'get_parents', 'when')