我有2个应用:Visitors
和Meetings
,通过ManytoMany
字段链接:
访问者/ 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:
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
管理面板中获取Visitors
会议的正确方法是:https://stackoverflow.com/a/18108586/2429989。
但是,如何在 list_display
管理面板中为每次会议的访问者显示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 "\n".join([a.visitor_name for a in obj.visitor.all()])
admin.site.register(Meeting, MeetingAdmin)
这导致'Meeting' object has no attribute 'visitor'
,我哪里错了?
答案 0 :(得分:2)
默认的反向查询关系始终为obj.tablename_set
。在您的情况下,您需要使用class ApplicationMailer < ActionMailer::Base
default from: 'hello@myapp.com'
layout 'mailer'
ADMIN_EMAIL = 'admin@myapp.com'
end
class AdminMailer < ApplicationMailer
default to: "#{ADMIN_EMAIL}"
def mandrill_client
@mandrill_client ||= Mandrill::API.new MANDRILL_API_KEY
end
def new_user(user)
#set required params
mandrill_client.messages.send_template template_name, template_content, message
end
end
obj.visitor_set.all()
但是,您可以通过定义related_name
:
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()])
所有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