django admin - 如何覆盖外键的默认<select>视图?</select>

时间:2010-01-27 20:04:20

标签: django-admin

我有2个django模型

class Location
  address = models.CharField(max_length=100)
  city = models.CharField(max_length=20)

class Client
  location = models.ForeignKey(Location)
  name = models.CharField(max_length=100)

我有以下admin.py

class ClientAdmin(admin.ModelAdmin):
fieldsets = [
    ('Client Details', {'fields': ['name']}),
    ('Location Details', {'fields': ['location']}),
]


admin.site.register(Client, ClientAdmin)

当我尝试添加客户端时,我希望有一个可编辑的“位置”字段,即地址和城市文本字段。 django默认给出一个列表..如何从foregin表中获取字段?

我能做到这一点吗?我不希望在管理员中注册位置表。

感谢

1 个答案:

答案 0 :(得分:2)

您可以为该位置放置一个内联表,并使用方法queryset来处理字段值。 所以,这是解决方案的意思:

class LocationInline(admin.StackedInline):
    model = Location

    def queryset(self, request):
        query = ... #your custom query here
        qs = super(LocationInline, self).queryset(request).filter(query)
        return qs


class ClientAdmin(admin.ModelAdmin):
    inlines = [LocationInline]
    fieldsets = [
        ('Client Details', {'fields': ['name']}),
    ]

修改 在django 1.1中还有另一种方法。

class ClientAdmin(admin.ModelAdmin):
    fieldsets = [
        ('Client Details', {'fields': ['name']}),
        ('Location Details', {'fields': ['location']}),
    ]

def formfield_for_foreignkey(self, db_field, request, **kwargs):

    if db_field.name = "location":
        locations = Location.objects.filter( ... ) #your query

        kwargs["queryset"] = Location.objects.filter(query)

    return super(ClientAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

文档在这里:http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_for_foreignkey

这是一个老问题,但回答这个问题也可以帮助很多其他人。 所以,我希望它有所帮助! ;)