0

我正在 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("Food Speciality",它们只属于 "Restaurants")。

所以我想用“餐厅”类别创建业务“Foster Hollywood”,我想在管理内联 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

4

1 回答 1

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)
于 2013-09-01T10:04:55.047 回答