【问题标题】:Create ModelChoiceField with annotation使用注释创建 ModelChoiceField
【发布时间】:2018-05-18 13:12:30
【问题描述】:

我需要制作一个带有性别(男性和女性)的选择器,以及每种类型的相应计数。

例如,如果我的数据库中有 4 个男性和 8 个女性,我需要一个带有选项的选择标签

  • “选择性别”
  • “男 (4)”
  • 《女(8)》

在我的Form 课程中

gender = forms.ModelChoiceField(
        queryset=Gender.objects.all().annotate(counter=Count('user')),
        required=False,
        label="Gender"
    )

而且我不知道如何呈现这个选择元素。如果我使用{{ form.gender }},我什至无法显示选项。我得到Error binding parameter 0 - probably unsupported type。可能是 SQLite 问题?无论如何我都会使用 PostgreSQL 作为我的数据库。

有什么建议吗?

编辑:我需要这样的东西,在每种情况下都有近 10 个表单字段和可变数量的选项

【问题讨论】:

  • 您应该使用ChoiceField 而不是ModelChoiceField,因为它呈现从查询集派生的元素检查此处docs.djangoproject.com/en/1.11/ref/forms/fields/…
  • @VaibhavMule ChoiceField 不支持queryset,我需要用数据库中的值填充它。还有其他想法吗?

标签: django forms annotations


【解决方案1】:

我会这样做。我试过了,效果很好。根据您的需要对其进行修改,它也应该可以正常工作。我只是在修改性别字段的小部件。

class testform(forms.ModelForm):
    class Meta:
        model = names
        fields = ['name', 'gender']

    male = 'male'+str(names.objects.filter(gender='m').count())
    female = 'female'+str(names.objects.filter(gender='f').count())
    choices = ((male, male),(female,female))
    gender = forms.CharField(widget=forms.Select(choices=choices))

【讨论】:

  • 我会试试这个。谢谢!有没有办法以更蟒蛇的方式制作它?我有 10 个这样的字段,选项编号从 2 到 13 或更多,所以我需要更通用的东西。我用我需要的图像更新我的问题。
【解决方案2】:

你可以覆盖ModelChoiceFieldlabel_from_instance方法:

class GenderModelChoiceField(forms.ModelChoiceField):
    def label_from_instance(self, obj):
        return obj.name + ' ({})'.format(obj.counter)

并在您的表单中使用此自定义字段:

gender = GenderModelChoiceField(
    queryset=Gender.objects.all().annotate(counter=Count('user')),
    required=False,
    label="Gender"
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-23
    • 2017-02-03
    • 1970-01-01
    • 2011-07-10
    • 1970-01-01
    • 2014-07-22
    • 2016-05-19
    相关资源
    最近更新 更多