110
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' 是不受支持的 ManyToManyField。

但是,当我'product'取出list_display. 那么我怎样才能'product'list_display不出错的情况下显示呢?

编辑ManyToManyField:也许一个更好的问题是你如何显示一个list_display

4

3 回答 3

200

您可能无法直接执行此操作。从文档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')
于 2013-08-07T16:22:01.263 回答
22

这样您就可以做到,请查看以下代码段:

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')
于 2015-06-16T11:17:51.403 回答
6

如果您想保存额外的查询,您可以添加一个prefetch_related


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

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        return qs.prefetch_related('product')

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

于 2021-05-21T15:28:40.993 回答