在Django Admin中过滤ManyToMany框
我有一个与另一个对象具有多对多关系的对象。
在Django Admin中,这会在多重选择框中产生很长的列表。
我想过滤掉ManyToMany关系,所以我只获取客户选择的城市中可用的类别。
这可能吗?我需要为其创建一个小部件吗?如果是这样,我该如何将行为从标准ManyToMany字段复制到该字段,因为我也希望filter_horizontal函数。
这些是我的简化模型:
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)
回答:
这是我使用上述类的解决方案。我添加了许多过滤器以正确过滤它,但我想在此处使代码可读。
这正是我一直在寻找的东西,我在这里找到了解决方案:http : //www.slideshare.net/lincolnloop/customizing-the-django-admin#stats-bottom(幻灯片50)
将以下内容添加到我的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 :))
ModelForms非常强大,令我感到惊讶的是它没有在文档/书中详细介绍。
以上是 在Django Admin中过滤ManyToMany框 的全部内容, 来源链接: utcz.com/qa/413982.html