在 Django Admin 中过滤多对多框 [英] Filter ManyToMany box in Django Admin

查看:23
本文介绍了在 Django Admin 中过滤多对多框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与另一个对象具有多对多关系的对象.
在 Django Admin 中,这会导致多选框中的列表很长.

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

我想过滤 ManyToMany 关系,因此我只获取客户选择的城市中可用的类别.

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

这可能吗?我必须为它创建一个小部件吗?如果是这样 - 我如何将标准 ManyToMany 字段中的行为复制到它,因为我也想要 filter_horizo​​ntal 函数.

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.

这些是我的简化模型:

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_horizo​​ntal :))

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 中过滤多对多框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆