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关系进行过滤操作,因此我只获取客户 Select 的城市中可用的类别.

这个是可能的吗?我需要为它创建一个小部件吗?如果是这样的话-我应该如何将行为从标准的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)
    categories = models.ManyToManyField(Category)

推荐答案

好的,这是我使用上述类的解决方案.

这正是我要找的,我在这里找到了解决方案: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

这会过滤"类别"列表,而不会删除任何功能!(即:我还可以拥有我心爱的过滤_Horizular:)

ModelForms非常强大,我有点惊讶在文档/书籍中没有更多地介绍它.

Django相关问答推荐

如果密码在Django中未被散列,则对其进行散列

try 在 django 中发送验证邮箱,出现错误

当前路径 **/POST 与其中任何一个都不匹配

通过get_form_kwargs将请求传递给Django表单未能使表单访问self.request.user.

在 Django 4.1 中提交表单之前显示数据

如何将多个模型添加到单个列表视图?

如何在视图中的 Django 重定向末尾附加字符串?

Django ORM:子查询上的文本聚合器

- 不支持的操作数类型:DateField和DateField

直接在模型类上使用 Django 管理器与静态方法

如何在不使用 sudo 的情况下安装 virtualenv?

验证 Django 模型对象的正确方法?

在 Django 网站上找不到页面 404?

django中的脏字段

从 virtualenv 中,pip freeze > requirements.txt 给出了一堆垃圾!如何修剪它?

如何使用 django-nose 运行单个测试或单个 TestCase?

Django unique=True 不工作

Table doesn't exist表不存在

get_or_create() 是否必须立即保存?

如何更改 django 模板中布尔值的打印方式?