Filter ManyToMany box in Django Admin

2019-01-16 01:26发布

I have a object with a many-to-many relation with another object.
In the Django Admin this results in a very long list in a multiple select box.

I'd like to filter the ManyToMany relation so I only fetch Categories that is available in the City that the Customer have selected.

Is this possible? Will I have to create a widget for it? And if so - how do I copy the behavior from the standard ManyToMany field to it, since I would like the filter_horizontal function as well.

These are my simplified models:

class City(models.Model):
    name = models.CharField(max_length=200)


class Category(models.Model):
    name = models.CharField(max_length=200)
    available_in = models.ManyToManyField(City)


class Customer(models.Model):
    name = models.CharField(max_length=200)
    city = models.ForeignKey(City)
    categories = models.ManyToManyField(Category)

7条回答
地球回转人心会变
2楼-- · 2019-01-16 02:16

Another way is with formfield_for_manytomany in Django Admin.

class MyModelAdmin(admin.ModelAdmin):
    def formfield_for_manytomany(self, db_field, request, **kwargs):
        if db_field.name == "cars":
            kwargs["queryset"] = Car.objects.filter(owner=request.user)
        return super(MyModelAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)

Considering that "cars" are the ManyToMany field.

Check this link for more info.

查看更多
登录 后发表回答