1

我有一个看起来像这样的对象结构:

客户——一对多——地点

地点——多对多——部门

部门——一对多——对象

这是我的 models.py(我的 admin.py 是标准的):

class Customer(models.Model):
    customerName = models.CharField(max_length=64)


class Department(models.Model):
    departmentName = models.CharField(max_length=64)


class Location(models.Model):
    customer = models.ForeignKey(Customer)
    departments = models.ManyToManyField(Department)


class Object(models.Model):
    location = models.ForeignKey(Location)
    department = models.ForeignKey(Department)

问题是,当我想为对象设置部门时,我会在 django admin 下拉菜单中找到每个部门。我什至得到与不同客户位置相关的部门。

此外,当我设置对象的部门时,我会得到所有可用部门的相同列表,甚至是与不同客户相关联的部门。

我怎样才能让下拉菜单只显示客户支持的部门?

4

3 回答 3

1

A quick one line solution to filter down a many to many relationship is put this line in your admin object:

filter_horizontal = ('departments',)

于 2013-06-12T23:38:52.267 回答
0

您可以为自己的表单提供过滤的查询集

class DepartmentAdminForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(DepartmentAdminForm, self).__init__(*args, **kwargs)
        self.fields['customers'].queryset = Customer.objects.filter(...)

    class Meta:
       model = Department


class DepartmentAdmin(admin.ModelAdmin):
    form = DepartmentAdminForm
于 2013-05-16T06:29:52.303 回答
0

我相信答案是使用 formfield_for_manytomany

https://docs.djangoproject.com/en/1.4/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_for_foreignkey

于 2013-05-17T16:38:08.213 回答