Adding a ManyToManyWidget to the reverse of a ManyToManyField in the Django Admin

前端 未结 5 1063
我寻月下人不归
我寻月下人不归 2020-12-13 07:08

Let\'s say I have a simple blog app in Django 1.4:

class Post(models.Model):
    title = …
    published_on = …
    tags = models.ManyToManyField(\'Tag\')

c         


        
5条回答
  •  臣服心动
    2020-12-13 07:40

    Modify your models to add reverse field:

    # models.py
    from django.db import models
    
    class Post(models.Model):
        title = models.CharField(max_length=100)
        published_on = models.DateTimeField()
        tags = models.ManyToManyField('Tag')
    
    class Tag(models.Model):
        name = models.CharField(max_length=10)
        posts = models.ManyToManyField('blog.Post', through='blog.post_tags')
    

    Then in standard way add field to ModelAdmin:

    #admin.py
    from django.contrib import admin
    
    class TagAdmin(admin.ModelAdmin):
        list_filter = ('posts', )
    
    admin.site.register(Tag, TagAdmin)
    

提交回复
热议问题