管理面板中多对多字段的

管理面板中多对多字段的

本文介绍了管理面板中多对多字段的 List_display的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have 2 apps: Visitors and Meetings, linked via a ManytoMany field:

visitors/models.py:

visitors/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

会议/models.py:

meetings/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

我知道在 Visitor 管理面板中为会议获取 list_display 的正确方法是:https://stackoverflow.com/a/18108586/2429989.

I know the correct way to get a list_display for meetings in the Visitors admin panel is here: https://stackoverflow.com/a/18108586/2429989.

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

However, how can I show a list_display for visitors at each meeting in the Meetings admin panel? I have tried:

会议/admin.py:

meetings/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 "
".join([a.visitor_name for a in obj.visitor.all()])

admin.site.register(Meeting, MeetingAdmin)

这导致 'Meeting' 对象没有属性 'visitor',我哪里出错了?

This results in 'Meeting' object has no attribute 'visitor', where am I going wrong?

推荐答案

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

The default reverse lookup relation it's always obj.tablename_set. In your case you need to use obj.visitor_set.all()

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

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

但是,您可以通过定义 related_name:

However, you can customize the name of the reverse lookup by defining the 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.像这样使用它:

All Meeting objects will now have access to visitors. Use it like:

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

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

这篇关于管理面板中多对多字段的 List_display的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 16:36