gpt4 book ai didi

python - 在 Django 上更改 ModelChoiceField 的查询集

转载 作者:太空宇宙 更新时间:2023-11-04 10:47:07 25 4
gpt4 key购买 nike

我正在尝试显示一个下拉列表,该下拉列表仅显示查询集中的某些对象,但要么出现错误,要么不显示任何对象,要么显示所有对象。

models.py
class Book(models.Model):
name = models.CharField(max_length=200, default='')
owner = models.CharField(max_length=200, default='')

def __unicode__(self):
return self.name

class DropDownList(forms.Form):
switch = forms.ModelChoiceField(queryset=Book.objects.none().order_by('name'), widget=forms.Select(attrs={"onChange":'submit()'}), required=False, initial=0)

def __init__(self, u, *args, **kwargs):
super(DropDownList, self).__init__(*args, **kwargs)
self.fields['switch'].queryset = Book.objects.filter(owner = u)


views.py
d = DropDownList('anthony')

当我尝试同步数据库时,我得到:“NameError: name 'u' is not defined我尝试使用 get(Q(owner = u)) 等其他方法进行过滤,但无济于事。我正在关注此片段中的信息 http://djangosnippets.org/snippets/2481/当我没有过滤其中包含的项目时,下拉列表正确显示。

最佳答案

检查你的代码:

  1. 如果您覆盖了 __init__ 方法,请不要忘记调用 super(...).__init__:

    class DropDownList(forms.Form):
    switch = forms.ModelChoiceField(queryset=Book.objects.none().order_by('name'), widget=forms.Select(attrs={"onChange": 'submit()'}), required=False, initial=0)

    def __init__(self, u, *args, **kwargs):
    super(DropDownList, self).__init__(*args, **kwargs)
    self.fields['switch'].queryset = Book.objects.filter(owner=u)
  2. 可能只是问题中的错误输入,但可以肯定的是,您使用的是 max_length arg,而不是 max_lenght:

    class Book(models.Model):
    name = models.CharField(max_length=200, default='')
    owner = models.CharField(max_length=200, default='')

    def __unicode__(self):
    return self.name

关于python - 在 Django 上更改 ModelChoiceField 的查询集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16538079/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com