在Django的limit_choices_to中使用字段值 [英] Use field value in limit_choices_to in Django

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

问题描述

我有两个型号ProjectGroup.我的小组属于一个特定的项目.我的群组的字段为project = ForeignKey(Project)parent = ForeignKey('self').

I have two models Project and Group. My groups belong to a specific project. My groups have the fields project = ForeignKey(Project) and parent = ForeignKey('self').

我可以使用limit_choices_to来确保外键parent中的选项仅由同一项目内的组组成吗?

Can I use limit_choices_to to make sure the options in foreign key parent only consist of groups inside the same project?

我在想类似的东西

def limit_choices_to(self):
    return {'project': self.project}

推荐答案

在模型级别上不可能做到这一点,但是您可以在表单的构造函数中更改此字段的查询集.

This is impossible to do at the model level but you can change the queryset for this field in the form's constructor.

class GroupForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(GroupForm, self).__init__(*args, **kwargs)
        if self.instance.project:
            self.fields['parent'].queryset = Group.objects.filter(
                                                project=self.instance.project)

更新:要在管理员中执行此操作,您必须设置

UPDATE: To do it in the admin you have to set the form attribute of the ModelAdmin:

class GroupAdmin(admin.ModelAdmin):
    form = GroupForm

这篇关于在Django的limit_choices_to中使用字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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