【问题标题】:Can I create a custom django modelchoicefield with a default queryset我可以使用默认查询集创建自定义 django 模型选择字段吗
【发布时间】:2012-11-26 14:53:07
【问题描述】:

我有一个带有 follow_by 字段的订单模型:

class order(models.Model):
   followed_by = models.ForeignKey(User, limit_choices_to={'groups__name': "Managers"})

我有几个这样的模型和这些模型的表格。默认情况下,表单显示一个 modelchoicefield 列出作为经理的用户。这可以。但是显示效果不好:它给出了用户名,我想要名字+姓氏。这会很好用:Change Django ModelChoiceField to show users' full names rather than usernames

除了现在在每一种形式中我都必须声明查询集以将用户限制为经理。我可以使用上述方法,以便自定义模型选择字段默认为我过滤的查询集。那么从一个表格中我可以说:

followed_by = ManagerUserModelChoiceField()

【问题讨论】:

    标签: django django-forms django-models


    【解决方案1】:

    你能在你的 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()
    

    【讨论】:

    • 这实际上是我尝试的第一件事,但在我声明以下内容时以我的形式:followed_by = UserModelChoiceField(),我得到 TypeError: __init__() 至少需要 2 个参数(1 个给定)。 (见下面我的回答)
    【解决方案2】:

    尝试将查询集作为参数传递给ManagerUserModelChoiceField 类。

    followed_by = ModelChoiceField(queryset = User.objects.filter(groups__name="Managers")
    

    【讨论】:

    • 哎呀 - 只需重新阅读您的问题。你已经说过你不想这样做:(
    【解决方案3】:

    在我对@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 新手,所以我不确定这是否是一件坏事,或者我是否应该以某种方式让它变得更好?我会很感激一些反馈。话虽如此,它似乎工作正常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-15
      • 1970-01-01
      • 2015-04-16
      • 2012-06-29
      • 2011-04-11
      • 2016-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多