多对多列表显示djang

2024-04-24 09:51:47 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

错误显示:

'PurchaseOrderAdmin.list_display[0]', 'product' is a ManyToManyField which is not supported.

但是,当我从list_display中取出'product'时,它会编译。那么,如何在不出错的情况下在list_display中显示'product'

编辑:也许更好的问题是如何在list_display中显示ManyToManyField


Tags: selfmodeladminmodels错误displayproductamount
2条回答

你可能不能直接做。From the documentation of ^{}

ManyToManyField fields aren’t supported, because that would entail executing a separate SQL statement for each row in the table. If you want to do this nonetheless, give your model a custom method, and add that method’s name to list_display. (See below for more on custom methods in 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')

这样做,请签出以下代码片段:

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

相关问题 更多 >