简体   繁体   中英

How to show Many-to-Many Field on Django Admin Panel?

I have 2 models, Product and Tag. The relation between product and tag is Many-to-Many Relationship.

How to show "tags" field on django admin panel? Currently the value is None when I am using the code below

models.py

class Tag(models.Model):
  name = models.CharField(max_length=200, null=True)

  def __str__(self):
    return self.name

class Product(models.Model):
  CATEGORY = (
    ('Indoor','Indoor'),
    ('Outdoor','Outdoor'),
  )

  name = models.CharField(max_length=200, null=True)
  price = models.FloatField(null=True)
  category = models.CharField(max_length=200, choices=CATEGORY)
  description = models.CharField(max_length=200, null=True)
  date_created = models.DateTimeField(auto_now_add=True, null=True)
  tags = models.ManyToManyField(Tag)

admin.py

@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
  list_display = ['id','name','price','category','tags']
  list_display_links = ['name']
  
  def tags(self):
    return self.tags.name

try this

@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    list_display = ['id', 'name', 'price', 'category', 'get_tags']
    list_display_links = ['name']

    def get_tags(self, obj):
        if obj.tags.all():
            return list(obj.tags.all().values_list('name', flat=True))
        else:
            return 'NA'

Refer this https://docs.djangoproject.com/en/3.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display

@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
  list_display = ['id','name','price','category','get_tags']
  list_display_links = ['name']
  
  def get_tags(self, instance):
    return [tag.name for tag in instance.tags.all()]

In Django 4.1 you don't need to pass the second param (instance of class), and can do smth like this:

@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
  list_display = ['id','name','price','category','get_tags']
  list_display_links = ['name']
  
  def get_tags(self):
    return [tag.name for tag in instance.tags.all()]

Also, you can detalize this field, and add decorator @admin.display example for add title for django admin. More details in docs: https://docs.djangoproject.com/en/4.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM