使用多个模型在Django Admin中反转内联

时间:2011-12-22 00:04:04

标签: python django

说我有一些django模型,类似这样:

class Address(models.Model):
    pass

class Person(models.Model):
    address = models.ForeignKey(Address)

class Store(models.Model):
    address = models.ForeignKey(Address)

class Company(models.Model):
    address = models.ForeignKey(Address)

因此,在Admin界面中,我希望能够编辑Person并使地址内联。

我知道可以这样做,

class Address(models.Model):
    person  = models.ForeignKey(Person, blank=True)
    store   = models.ForeignKey(Store, blank=True)
    company = models.ForeignKey(Company, blank=True)

class Person(models.Model):
    pass

class Store(models.Model):
    pass

class Company(models.Model):
    pass

然后我可以照常做到,

class AddressInline(admin.TabularInline):
    model = Address

class PersonAdmin(admin.ModelAdmin):
    model = Person
    inlines = (AddressInLine,)

class CompanyAdmin(admin.ModelAdmin):
    and so on

但这意味着每个人都有多个地址,我的地址模型不再适合了。

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:6)

尝试以下

from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

class Address(models.Model):
    object_id    = models.PositiveIntegerField()
    content_type = models.ForeignKey(ContentType)
    of           = generic.GenericForeignKey('content_type', 'object_id' )

class Person(models.Model):
    pass

class Store(models.Model):
    pass

class Company(models.Model):
    pass

然后你可以这样做:

from django.contrib import admin
from django.contrib.contenttypes import generic

class AddressInline(generic.GenericStackedInline):
    model   = Address
    max_num = 1

class PersonAdmin(admin.ModelAdmin):
    model = Person
    inlines = (AddressInLine,)

class CompanyAdmin(admin.ModelAdmin):
    and so on

admin.site.register(Person, PersonAdmin)

答案 1 :(得分:3)

将类AddressInline(admin.TabularInline)更改为类AddressInline(admin.StackedInline)将使地址内联看起来不像可能有几个。

如果每个AddressInline不需要超过1个地址,请将AddressInline.max_num设置为1。

如果您在没有相关地址时需要空白地址表单,请将AddressInline.extra设置为1。

文档:https://docs.djangoproject.com/en/dev/ref/contrib/admin/#inlinemodeladmin-options