如何在DJango管理界面中显示ForeignKey反向查找列表? [英] How to I show a list of ForeignKey reverse lookups in the DJango admin interface?
问题描述
我有几个模型:
class Customer(models.Model):
customer_name = models.CharField(max_length=200)
def __unicode__(self):
return self.customer_name
class Meta:
ordering = ('customer_name',)
class Unit(models.Model):
unit_number = models.IntegerField()
rentable = models.BooleanField()
owner = models.ForeignKey(Customer, related_name='units', blank=True, null=True)
def __unicode__(self):
return str(self.unit_number)
class Meta:
ordering = ('unit_number',)
我的管理界面正常工作我添加了一个单位(我可以选择哪个客户分配给它),但是当我在DJango管理界面中创建/编辑客户时,它不列出任何可供选择的单位。如何在该部分中启用查找以匹配创建/编辑客户区域中的查找?
I have the admin interface working fine when I'm adding a unit (I can select which customer to assign it to) but when I go to create/edit a customer in the DJango admin interface, it doesn't list any units to choose from. How can I enable the lookup in that section to match the one in the create/edit customer area?
推荐答案
默认情况下, ModelAdmin只能让你管理模型本身,而不是相关模型。为了编辑相关的Unit模型,您需要定义一个InlineModelAdmin,例如admin.TabularInline,并将其附加到您的CustomerAdmin。
By default, a ModelAdmin will only let you manage the model "itself", not related models. In order to edit the related Unit model, you need to define an "InlineModelAdmin" - such as admin.TabularInline - and attach it to your CustomerAdmin.
https://docs.djangoproject.com/en/dev/ref/contrib/admin/#inlinemodeladmin-对象
例如,在您的admin.py中:
For example, in your admin.py:
from django.contrib import admin
from models import Customer, Unit
class UnitInline(admin.TabularInline):
model = Unit
class CustomerAdmin(admin.ModelAdmin):
inlines = [
UnitInline,
]
admin.site.register(Customer, CustomerAdmin)
这篇关于如何在DJango管理界面中显示ForeignKey反向查找列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!