我有两个型号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)更新:要在管理员中执行此操作,您必须设置 ModelAdmin的form 属性:
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
发布评论