gpt4 book ai didi

django - 管理面板中多对多字段的 List_display

转载 作者:行者123 更新时间:2023-12-04 02:00:45 26 4
gpt4 key购买 nike

我有 2 个应用程序:VisitorsMeetings ,通过 ManytoMany 链接 field :

访客/models.py:

from django.db import models
from meetings.models import Meeting

class Visitor(models.Model):

visitor_name = models.CharField(default='name', max_length=128, blank=False, null=False)
visitor_meetings = models.ManyToManyField(Meeting)

def __str__(self):
return self.visitor_name

session /models.py:
from django.db import models
from team.models import Team

class Meeting(models.Model):
team_member = models.ForeignKey(Team)
meeting_name = models.CharField(default='name', max_length=128, blank=True, null=True)

def __str__(self):
return self.meeting_name

我知道获得 list_display 的正确方法用于 session Visitors管理面板在这里: https://stackoverflow.com/a/18108586/2429989 .

但是,如何显示 list_display 中为每次 session 的访客Meetings 管理面板?我试过了:

session /admin.py:
from django.contrib import admin
from .models import Meeting
from visitors.models import Visitor

class MeetingAdmin(admin.ModelAdmin):
list_display = ['id', 'team_member', 'show_visitors' ]

def show_visitors(self, obj):
return "\n".join([a.visitor_name for a in obj.visitor.all()])

admin.site.register(Meeting, MeetingAdmin)

这导致 'Meeting' object has no attribute 'visitor' ,我哪里错了?

最佳答案

默认的反向查找关系总是 obj.tablename_set .在您的情况下,您需要使用 obj.visitor_set.all()

class MeetingAdmin(admin.ModelAdmin):
list_display = ['id', 'team_member', 'show_visitors' ]

def show_visitors(self, obj):
return "\n".join([a.visitor_name for a in obj.visitor_set.all()])

但是,您可以通过定义 related_name 来自定义反向查找的名称。 :
class Visitor(models.Model):
visitor_name = models.CharField(default='name', max_length=128, blank=False, null=False)
visitor_meetings = models.ManyToManyField(Meeting, related_name='visitors')

def __str__(self):
return self.visitor_name

全部 Meeting对象现在可以访问 visitors .像这样使用它:
class MeetingAdmin(admin.ModelAdmin):
list_display = ['id', 'team_member', 'show_visitors' ]

def show_visitors(self, obj):
return "\n".join([a.visitor_name for a in obj.visitors.all()])

关于django - 管理面板中多对多字段的 List_display,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31475104/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com