在Django Admin中过滤ManyToMany框 [英] Filter ManyToMany box in Django Admin
问题描述
我有一个与另一个对象具有多对多关系的对象。
在Django管理中,这会导致多个选择框中的很长列表。
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.
我想过滤ManyToMany关系,所以我只能获取客户选择的City中提供的类别。
I'd like to filter the ManyToMany relation so I only fetch Categories that is available in the City that the Customer have selected.
这可能吗?我必须为它创建一个小部件吗?如果是这样 - 我如何将标准的ManyToMany字段的行为复制到它,因为我也想要filter_horizontal函数。
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.
这些是我的简化模型: / p>
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)
推荐答案
好的,这是我使用上述类的解决方案。
我添加了一堆更多的过滤器来过滤它,但是我想使代码在这里可读。
Ok, this is my solution using above classes. I added a bunch more filters to filter it correctly, but I wanted to make the code readable here.
这正是我正在寻找的,我在这里找到我的解决方案: http://www.slideshare.net / lincolnloop / customizing-the-django-admin#stats-bottom (幻灯片50)
This is exactly what I was looking for, and I found my solution here: http://www.slideshare.net/lincolnloop/customizing-the-django-admin#stats-bottom (slide 50)
将以下内容添加到我的admin.py:
Add the following to my admin.py:
class CustomerForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(CustomerForm, self).__init__(*args, **kwargs)
wtf = Category.objects.filter(pk=self.instance.cat_id);
w = self.fields['categories'].widget
choices = []
for choice in wtf:
choices.append((choice.id, choice.name))
w.choices = choices
class CustomerAdmin(admin.ModelAdmin):
list_per_page = 100
ordering = ['submit_date',] # didnt have this one in the example, sorry
search_fields = ['name', 'city',]
filter_horizontal = ('categories',)
form = CustomerForm
这将过滤类别列表而不删除任何功能! (即:我仍然可以拥有我亲爱的filter_horizontal:))
This filters the "categories" list without removing any functionality! (ie: i can still have my beloved filter_horizontal :))
ModelForms非常强大,我有点惊讶,它在文档/书中没有涵盖更多。
The ModelForms is very powerful, I'm a bit surprised it's not covered more in the documentation/book.
这篇关于在Django Admin中过滤ManyToMany框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!