Atma
Atma

Reputation: 29765

django many to many admin shows all and not associated items

I have an object structure that looks like so:

Customer -- one to many -- Locations

Locations -- many to many -- Departments

Departments -- one to many -- Objects

here is my models.py (my admin.py is standard):

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)

The problem is that when I want to set the department for objects I get every department in the django admin drop down. I even get the departments that are associate with locations of different customers.

Also, when I am setting the department of an object, I get the same list of all available departments, even those associated with different customers.

How can I have the drop down only show me the departments that a customer supports?

Upvotes: 1

Views: 843

Answers (3)

Atma
Atma

Reputation: 29765

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

filter_horizontal = ('departments',)

Upvotes: 1

Atma
Atma

Reputation: 29765

I believe the answer is to use the formfield_for_manytomany

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

Upvotes: 0

Dmitry Demidenko
Dmitry Demidenko

Reputation: 3407

You can provide your own form with filtered queryset

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

Upvotes: 0

Related Questions