简体   繁体   English

如何在 Django 管理面板上显示多对多字段?

[英]How to show Many-to-Many Field on Django Admin Panel?

I have 2 models, Product and Tag.我有 2 个模型,产品和标签。 The relation between product and tag is Many-to-Many Relationship.产品和标签之间的关系是多对多关系。

How to show "tags" field on django admin panel?如何在 django 管理面板上显示“标签”字段? Currently the value is None when I am using the code below当我使用下面的代码时,当前值为 None

models.py模型.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管理员.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请参阅此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:在 Django 4.1 你不需要传递第二个参数(类的实例),并且可以这样做:

@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.另外,您可以对该字段进行细化,并添加装饰器@admin.display示例,为 django admin 添加标题。 More details in docs: https://docs.djangoproject.com/en/4.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display文档中的更多详细信息: https://docs.djangoproject.com/en/4.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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