在Django的limit_choices_to中使用字段值 [英] Use field value in limit_choices_to in Django
问题描述
我有两个型号Project
和Group
.我的小组属于一个特定的项目.我的群组的字段为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屋!