Django formset如何为modelforms中的每个表单提供不同的queryset

2024-05-29 04:06:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个模型表单-ClinicallyReportedSample,它链接到一个样本模型。在

我正在尝试为ClinicallyReportedSample创建一个formset,其中基于Sample的queryset,将显示特定数量的表单,以便用户可以添加数据。在

目前,样本模型有条目,但ClinicallyReportedSample模型完全为空:

型号:

class Sample(models.Model):

    request_number = models.PositiveIntegerField()
    year = models.PositiveIntegerField()


    class Meta:
        db_table = "sample"
        unique_together = (('request_number', 'year'),)

    def __str__(self):
        return("%s/%s" %(self.request_number, self.year))



class ClinicallyReportedSample(models.Model):

    sample_id = models.ForeignKey(Sample,
                                on_delete=models.CASCADE,
                                db_column='sample_id')


    reported = models.BooleanField(default=False)
    evidence = models.TextField(null=True, blank=True)

    ... other fields ...

    class Meta:
        db_table = "clinically_reported_sample"
        unique_together = (('sample_id'),)

    def __str__(self):
        clinically_reported_sample = str(self.sample_id)
        return(clinically_reported_sample)

我想要一个表单集中与样本模型的查询集相关的clinicallyReportedSampleModel表单。在

例如,具有pk 1、2和3的示例对象:

在表单.py公司名称:

^{pr2}$

所以我尝试在我的表单集中使用queryset

在视图.py公司名称:

def get(self, request, *args, **kwargs):


    sample_obj = Sample.objects.filter(id__in=[1, 2, 3])

    formset = modelformset_factory(
                ClinicallyReportedSample,
                form=self.crsform,
                formset=BaseCRSFormSet,
                extra=3,
            )


    formset = formset(queryset=sample_obj)

但这显示为三种形式,对于所有示例对象,queryset不起作用。这样做是正确的吗?在


Tags: sample模型selfid表单numbermodelsrequest
1条回答
网友
1楼 · 发布于 2024-05-29 04:06:49

您需要将默认的Sample queryset设置为none:

class CRSForm(forms.ModelForm):

    class Meta:
        model = ClinicallyReportedSample
        fields = ('sample_id', 'evidence',)

    sample_id = forms.ModelChoiceField(queryset=Sample.objects.none())

    def __init__(self, *args, **kwargs):
        super(CRSForm, self).__init__(*args, **kwargs)

然后,当您创建一个formset实例时,手动分配queryset,如下所示:

^{pr2}$

请注意,您还必须在POST函数中手动设置queryset,否则它将无法验证。在

相关问题 更多 >

    热门问题