many-to-many in list display django

后端 未结 2 1541
醉梦人生
醉梦人生 2020-12-02 08:22
class PurchaseOrder(models.Model):
    product = models.ManyToManyField(\'Product\')
    vendor = models.ForeignKey(\'VendorProfile\')
    dollar_amount = models.Flo         


        
相关标签:
2条回答
  • 2020-12-02 09:02

    This way you can do it, kindly checkout 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 admin.py module call method as follows:

    class categories(admin.ModelAdmin):
        list_display    = ('title', 'get_parents', 'when')
    
    0 讨论(0)
  • 2020-12-02 09:03

    You may not be able to do it directly. 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.)

    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 that

    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 the admin list_display

    list_display = ('get_products', 'vendor')
    
    0 讨论(0)
提交回复
热议问题