1

Event次のように、への一般的なインライン関係で名前が付けられた django モデルがありRelationshipます。

# models.py

class Person(models.Model):
    ...

class Role(models.Model):
    ...

class Event(models.Model):
    ...

class Relationship(models.Model):
    person = models.ForeignKey(Person)
    role = models.ForeignKey(Role)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey("content_type", "object_id")

# admin.py

class RelationshipInline(generic.GenericTabularInline):
    model = Relationship
    extra = 0

class EventAdmin(admin.ModelAdmin):
    inlines = [RelationshipInline]

イベント管理ページだけでなく、ユーザー管理ページからもインラインを編集する方法を見つけたいと思います。これまでのところ、ピープルページにもインラインを表示するために次のコードを追加しました

class ReverseRelationshipInline(admin.TabularInline):
    model = Relationship

class IndividualAdmin(admin.ModelAdmin):
    inlines = [ReverseRelationshipInline]

しかし、フォームのフィールドを取得content_typeobject_idますが、主キーへの参照にすぎないため、管理者ユーザーにとってはあまり情報がありません。解決して表示することをお勧めしますcontent_object(編集できない場合でも、リストで人がどのオブジェクトに関連しているかを知ることができます)。

おすすめの向きは?

ありがとう。

4

1 に答える 1

1

「ReverseRelationshipInline」は、TabularInline ではなく、GenericTabularInline である必要があります。それで全部です :-)

アップデート

私はあなたが求めているものを理解したと思います。私の答えは次のとおりです。

Person のコンテンツ オブジェクトをインラインで編集することはできませんが、変更フォームへのリンクとして表示することもできます。

このような HTML リンクを返す関数を Relationship に追加し、独自の ModelForm をインラインに提供し、必要なフィールドを指定します。これには、新しい関数値 (読み取り専用) が含まれるようになりました。このようなもの(テストされていません):

# models.py

from django.core import urlresolvers

class Relationship(models.Model):
    ...
    def link_content_object_changeform(self):
        obj = self.content_object
        change_url = urlresolvers.reverse(
            'admin:%s_%s_change' % (
                obj._meta.app_label,
                obj._meta.object_name.lower()
            ),
            args=(obj.id,)
        )
        return u'<a href="%s">%s</a>' % (change_url,  obj.__unicode__())
    link_content_object_changeform.allow_tags = True
    link_content_object_changeform.short_description = 'in relation to'

# admin.py

class ReverseRelationshipInlineForm(forms.ModelForm):
    class Meta:
        model = Relationship
        fields = ('person', 'role', 'link_content_object_changeform')
        readonly_fields = ('link_content_object_changeform',)

class ReverseRelationshipInline(admin.TabularInline):
    model = Relationship
    form = ReverseRelationshipInlineForm
于 2012-08-14T22:36:09.407 に答える