Many-to-many on django's display list

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 

I have this code. Unfortunately, an error occurs in admin.py using ManyToManyField

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

The error says:

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

However, it compiles when I take the 'product' from list_display . So how can I display 'product' in list_display without errors?

edit . Perhaps the best question is: how do you display ManyToManyField in list_display ?

+44
python django django-admin django-queryset admin
Aug 07 '13 at 16:18
source share
2 answers

You may not be able to do this directly. From the list_display documentation

ManyToManyField fields are supported, as this would entail executing a separate SQL statement for each row in the table. if you want to do this, however, give your model your own method and add that methods to name to list_display. (For more details, see below. Methods in list_display.)

You can do something like this:

 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()]) 

OR define a model method and use this

 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()]) 

and in admin list_display

 list_display = ('get_products', 'vendor') 
+91
Aug 07 '13 at 16:22
source share

So you can do this, kindly look at the following snippet:

 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) 

And in your method of calling admin.py module do the following:

 class categories(admin.ModelAdmin): list_display = ('title', 'get_parents', 'when') 
+6
Jun 16 '15 at 11:17
source share



All Articles