在Django的limit

编程入门 行业动态 更新时间:2024-10-14 12:28:14
本文介绍了在Django的limit_choices_to中使用字段值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有两个型号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

本文发布于:2023-11-27 13:10:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1638209.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Django   limit

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!