我是否可以使用默认查询集创建自定义django modelchoicefield

我是否可以使用默认查询集创建自定义django modelchoicefield,django,django-forms,django-models,Django,Django Forms,Django Models,我有一个订单模型,后跟一个字段: class order(models.Model): followed_by = models.ForeignKey(User, limit_choices_to={'groups__name': "Managers"}) 我有几个这样的模型和这些模型的表格。默认情况下,表单会显示一个modelchoicefield,其中列出了作为经理的用户。这很好。但是显示不好:它给出了用户名,我想要名字+姓氏。这将很好地发挥作用: 除了现在在everyform中,我

我有一个订单模型,后跟一个字段:

class order(models.Model):
   followed_by = models.ForeignKey(User, limit_choices_to={'groups__name': "Managers"})
我有几个这样的模型和这些模型的表格。默认情况下,表单会显示一个modelchoicefield,其中列出了作为经理的用户。这很好。但是显示不好:它给出了用户名,我想要名字+姓氏。这将很好地发挥作用:

除了现在在everyform中,我必须声明queryset以将用户限制为经理。我是否可以使用上述方法,使自定义modelchoicefield默认为我的筛选queryset。那么从表格上我可以说:

followed_by = ManagerUserModelChoiceField()

能否在ModelChoiceField子类上定义查询集

class UserModelChoiceField(ModelChoiceField):
    # Query that returns set of valid choices
    queryset = User.objects.filter(group__name='Managers')
    def label_from_instance(self, obj):
        return obj.get_full_name()

尝试将queryset作为参数传递给ManagerUserModelChoiceField类


在我对@Enrico发表评论后,我想到了一个想法:我在自定义字段上重写了init类,如下所示:

class UserModelChoiceField(forms.ModelChoiceField):
    def __init__(self, *args, **kwargs):
        super(UserModelChoiceField, self).__init__(queryset=User.objects.filter(groups__name="Managers"), *args, **kwargs)

我以前在python中见过类似的东西,但我对python是新手,所以我不确定这样做是不是一件坏事,或者我是否应该以某种方式改进它?我希望得到一些反馈。话虽如此,它似乎工作正常。

哎哟-请重新阅读您的问题。您已经说过不想这样做:这实际上是我尝试的第一件事,但在我声明以下内容时,以我的形式:后跟=UserModelChoiceField,我得到TypeError:\uuuuu init\uuuu至少接受2个参数1。见下面我的答案
class UserModelChoiceField(forms.ModelChoiceField):
    def __init__(self, *args, **kwargs):
        super(UserModelChoiceField, self).__init__(queryset=User.objects.filter(groups__name="Managers"), *args, **kwargs)