我在Django管理员中创建一个内联表单,假设有条件值。
例如,我有这个模型
class Category (models.Model):
name = models.CharField(max_length=500)
parent = models.ForeignKey('self', blank=True, null=True, related_name='subcategory')
def __unicode__(self):
return self.name
class Business(models.Model):
category = models.ForeignKey(Category)
name = models.CharField(max_length=500)
def __unicode__(self):
return self.name
class DescriptionType (models.Model):
category = models.ManyToManyField(Category)
name = models.CharField(max_length=500)
def __unicode__(self):
return self.name
class Descriptions (models.Model):
descriptiontype = models.ForeignKey(DescriptionType)
business = models.ForeignKey(Business)
所以,我有Category
(“餐馆”)和DescriptionType
(“食品专业”,只属于“餐馆”)。
所以我想用类别“restaurant”创建商业“福斯特好莱坞”,我想在管理内联DescriptionsInline只允许选择属于“餐馆”类别的DescriptionTypes。我当前的解决方案显示描述类型的所有值
class DescriptionsInline(admin.TabularInline):
model = Descriptions
extra = 0
class BusinessAdmin(admin.ModelAdmin):
inlines = [DescriptionsInline]
list_display = ('name',)
search_fields = ['name']
admin.site.register(Business, BusinessAdmin)
如何才能使内联DescriptionsInline
仅显示DescriptionTypes
所选类别中的Business
?
答案 0 :(得分:1)
我在http://www.stereoplex.com/blog/filtering-dropdown-lists-in-the-django-admin
找到了解决方案class DescriptionsInline(admin.TabularInline):
model = Descriptions
exclude = ['modified']
extra = 0
def formfield_for_dbfield(self, field, **kwargs):
if field.name == 'descriptiontype':
parent_business = self.get_object(kwargs['request'], Business)
if parent_business == None:
related_descriptiontype = DescriptionType.objects.all()
else:
related_descriptiontype = DescriptionType.objects.filter(category=parent_business.category_id)
return forms.ModelChoiceField(queryset=related_descriptiontype)
return super(DescriptionsInline, self).formfield_for_dbfield(field, **kwargs)
def get_object(self, request, model):
object_id = request.META['PATH_INFO'].strip('/').split('/')[-1]
try:
object_id = int(object_id)
except ValueError:
return None
return model.objects.get(pk=object_id)