python - 列表显示django中的多对多

标签 python django django-admin admin django-queryset

class Product(models.Model):
    products = models.CharField(max_length=256)
    
    def __unicode__(self):
        return self.products

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

我有那个代码。不幸的是,错误出现在带有 ManyToManyField

的 admin.py 中
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' 而不会出错?

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

最佳答案

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

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

关于python - 列表显示django中的多对多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18108521/

相关文章:

python - 如何在类中使用 Python 中的多重处理

python - VTK:使用 vtkDelaunay2D 创建多边形和孔不起作用

python - django-recaptcha 不验证输入

javascript - 在 django 中显示图像

Python - 如何使用 Pandas 编辑基于另一个 CSV 的 CSV

python - 序列化多个模型并在一个 json 响应中发送所有模型 django rest framework

python - 上下文不打印 Django

python - 如何对 Django 管理内联表单进行单元测试

django - 为什么 Django 会抛出系统错误?

django - 将图像上传到 Django admin,进行裁剪和缩放,然后将其发送到 Amazon S3,而不在本地保存文件?