如何在Django ModelForm中引用当前对象?

时间:2018-03-21 23:31:30

标签: python django

我有两个相关模型,test.a == 0Company。每个公司可以有几个包,但只有一个Package。以下是模型:

default_package

class Company(models.Model): default_package = models.OneToOneField( Package, blank=True, null=True, related_name='default_for_%(class)s')

Package

我尝试为公司制作通用class Package(TimeStampedModel): company = models.ForeignKey('lucy_web.Company') CreateView,如下所示:

UpdateView

class EditViewsMixin(DashboardAccessMixin, SuccessMessageMixin): model = Company success_url = reverse_lazy('dashboard:companies') form_class = CompanyForm class CompanyCreate(EditViewsMixin, CreateView): template_name = 'companies/new.html' success_message = "Company '%(name)s' was created successfully" class CompanyUpdate(EditViewsMixin, UpdateView): template_name = 'companies/edit.html' success_message = "Company '%(name)s' was updated successfully" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['packages'] = self.object.package_set.order_by('name') return context 类似于以下内容:

CompanyForm

问题在于,在这种形式下,class CompanyForm(forms.ModelForm): class Meta: model = Company fields = [ 'name', 'default_package', ] 下拉菜单显示了所有包,而我希望它包含在所考虑公司的default_package中的包中,类似于通过在视图的package_set方法中引用self.object来完成。

从本质上讲,我想在get_context_data中做这样的事情:

CompanyForm

但是,这是不可能的,因为default_package = forms.ModelChoiceField( queryset=Package.objects.filter(company=self.instance) ) 未在此级别定义。对于特定字段,是否存在self类似ModelForm的某种方法,我可以使用get_queryset定义查询集?

1 个答案:

答案 0 :(得分:1)

我设法通过更新ModelForm's __init__()中的字段来完成此操作,如下所示:

def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.fields['default_package'].queryset = Package.objects.filter(company=self.instance)