Django Admin: Many-to-Many listbox doesn't show up with a through parameter

前端 未结 4 1311
灰色年华
灰色年华 2021-02-01 08:42

I have the following models:

class Message(models.Model):
    date = models.DateTimeField()
    user = models.ForeignKey(User)    
    thread = models.ForeignKey         


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-01 09:01

    Django admin nicely support many-to-many intermediary models that using the through argument .

    For example you have these Person and Group models with intermediate Membership model:

    models.py

    from django.db import models
    
    class Person(models.Model):
        name = models.CharField(max_length=128)
    
    class Group(models.Model):
        name = models.CharField(max_length=128)
        members = models.ManyToManyField(Person, through='Membership')
    
    class Membership(models.Model):
        person = models.ForeignKey(Person, on_delete=models.CASCADE)
        group = models.ForeignKey(Group, on_delete=models.CASCADE)
        date_joined = models.DateField()
        invite_reason = models.CharField(max_length=64)
    

    Now in admin.py file , Define an inline class for the intermediate Membership model:

    @admin.register(Membership)
    class MembershipInline(admin.TabularInline):
        model = Membership
        extra = 1
    

    And use them in admin views of models:

    @admin.register(Person)
    class PersonAdmin(admin.ModelAdmin):
        inlines = (MembershipInline,)
    
    @admin.register(Group)
    class GroupAdmin(admin.ModelAdmin):
        inlines = (MembershipInline,)
    

    More info in official docs:

    Models, Admin

提交回复
热议问题