如果你有我称之为“中间”的ManyToMany表,那就很简单了:
class Interrogation(models.Model):
phrases = models.ManyToManyField(Phrase, blank=True,
through='InterrogationPhrase',
symmetrical=False,
related_name='phrase')
class InterrogationPhrase(models.Model):
interrogation = models.ForeignKey(Interrogation, blank=False)
phrase = models.ForeignKey(Phrase, blank=False)
def __str__(self):
return u'({0}) - {1} - {2}'.format(
self.importance, self.interrogation, self.phrase
)
使用上面的代码,在“Inline
”管理员中,如果我只是声明,则会显示__str__
InterrogationPhrase
:
class InterrogationPhrasesInline(CollapsedStackedInline):
model = InterrogationPhrase
fk_name = 'interrogation'
fields = ('phrase')
extra = 0
verbose_name = _(u"Phrase")
verbose_name_plural = _(u"Phrases")
但是当我不想要中间声明并且我只想写时如何处理:
class Mot(models.Model):
groupes = models.ManyToManyField(Groupe)
没有声明MotGroupe
表(在Django中允许)?我的管理员看起来像这样:
class MotGroupesInline(CollapsedStackedInline):
model = Mot.groupes.through
extra = 0
verbose_name = _(u"Groupe")
verbose_name_plural = _(u"Groupes")
class MotAdmin(admin.ModelAdmin):
inlines = (MotGroupesInline,)
但问题是,对于Groupe
的每一行,内联显示为:Groupe: Mot_groupes object
。这既丑陋又毫无用处。如何改变?
答案 0 :(得分:2)
您可以使用Proxy models。
我的models.py
:
# coding: utf-8
from __future__ import unicode_literals
from django.db import models
class Groupe(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
class Mot(models.Model):
name = models.CharField(max_length=255)
groupes = models.ManyToManyField(Groupe)
def __str__(self):
return self.name
class MotGroupeProxy(Mot.groupes.through):
class Meta:
proxy = True
def __str__(self):
return str(self.groupe)
我的admin.py
:
# coding: utf-8
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from so_34111398_manytomany_inline.models import Mot, Groupe, MotGroupeProxy
class MotGroupesInline(admin.StackedInline):
model = MotGroupeProxy
extra = 0
verbose_name = _(u"Groupe")
verbose_name_plural = _(u"Groupes")
@admin.register(Mot)
class MotAdmin(admin.ModelAdmin):
inlines = (MotGroupesInline,)
@admin.register(Groupe)
class GroupeAdmin(admin.ModelAdmin):
pass