Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Django中使用limit_choices_to中的字段值_Django_Django Models_Django Mptt - Fatal编程技术网

在Django中使用limit_choices_to中的字段值

在Django中使用limit_choices_to中的字段值,django,django-models,django-mptt,Django,Django Models,Django Mptt,我有两种型号Project和Group。我的组属于一个特定的项目。我的组有字段project=ForeignKey(project)和parent=ForeignKey('self') 我是否可以使用limit\u choices\u to来确保外键parent中的选项仅由同一项目中的组组成 我在想类似的事情 def limit_choices_to(self): return {'project': self.project} 这在模型级别是不可能做到的,但是您可以在表单的构造函数中

我有两种型号
Project
Group
。我的组属于一个特定的项目。我的组有字段
project=ForeignKey(project)
parent=ForeignKey('self')

我是否可以使用
limit\u choices\u to
来确保外键
parent
中的选项仅由同一项目中的组组成

我在想类似的事情

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

这在模型级别是不可能做到的,但是您可以在表单的构造函数中更改此字段的queryset

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)
更新:要在管理员中执行此操作,必须设置
模型管理员的属性

class GroupAdmin(admin.ModelAdmin):
    form = GroupForm

非常感谢。但是我怎样才能在管理部分实现同样的结果呢?我想,这应该可以在模型级别通过
limit\u choices\u to={'project\u id':Value('id')}
实现,但是我得到的错误像
psycopg2.errors.InvalidCursorName:cursor“\u django\u curs\u 140361007625984\u sync\u 1”不存在