django-select2小部件的查询集被忽略 [英] Queryset for django-select2 widget being ignored

查看:77
本文介绍了django-select2小部件的查询集被忽略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,我大量使用Django-Select2,尤其是它的ModelSelect2Widget,因为我的用户经常需要从2,000-6,000项列表中进行选择。到目前为止,在我的所有使用中,小部件的查询集始终被称为模型的 .all()实例,供用户选择,并且没有任何问题。

In my project I am using Django-Select2 heavily, particularly its ModelSelect2Widget as my users frequently need to select from lists of 2,000-6,000 items. In all my uses of it up 'til now, the queryset for the widget has always been called as ".all()" instances of a model, for the user to select from, and there's been no issues.

但是,现在,我在项目的不同部分中都有实现,对于这些实现,必须过滤小部件的选项的查询集。但是,在所有这些情况下,对queryset的任何修改似乎都无效,我想知道小部件本身是否存在问题。

Now, however, I have implementations in different parts of the project for which filtering the queryset of options for the widget is necessary. In all of these cases, however, any modification of the queryset seems to have no effect, and I'm wondering if there is a problem with the widget itself.

在主要情况下,数据库中的项目被布尔标记为活动/非活动(大约65%为非活动),我只需要为

In the primary case, the items in the database are boolean-flagged as active/inactive (about 65% inactive), and I need to only have active items available for the end-user to select.

我能够通过外壳正确过滤查询。

I'm able to filter the queries correctly via the shell.

在形式定义中,任何过滤( .filter(flag_active = True),甚至将查询集设置为 .none())都无效–下拉菜单/自动完成中的选项没有明显变化。这是一个select2输入,我一次只能查看少量项目,但是在我键入时,初始检索的总体和winnowed-down选择都表明未遵循过滤器。

In the form definitiion, any filtering (".filter(flag_active=True)", or even setting the queryset to ".none()" has no effect – there is no apparent change in the options in the dropdown/autocomplete. Being that it is a select2 input, I can only view a small number of items at a time, but both the initial retrieved population and the winnowed-down selection as I type indicate that the filters are not been followed.

MODEL:

class Inventory_product_base(models.Model):
    id = models.UUIDField(primary_key=True,default=uuid.uuid4,null=False)
    upc = models.CharField(max_length=96,null=True,blank=True)
    name = models.CharField('Item name',max_length=96,null=False)
    flag_active = models.BooleanField("Active item",default=True)
    price = models.DecimalField(max_digits=8,decimal_places=3,null=True,blank=True)
    unit_of_measure = models.CharField('UOM',max_length=24, choices=UNITS_OF_MEASURE,default='EACH')
    spec = models.CharField(max_length=36,null=True,blank=True)
    category = models.ForeignKey(Inventory_category,on_delete=models.CASCADE,related_name='cat_products')
    subcategory = models.ForeignKey(Inventory_subcategory,on_delete=models.CASCADE,related_name='subcat_products')
    note = models.CharField(max_length=275,null=True,blank=True)

    def __str__(self):
        return str(self.name)

FORM:

class InventoryCatalogUpdateProductsForm(forms.ModelForm):
    parent_product_base = forms.ModelChoiceField(
        queryset=Inventory_product_base.objects.filter(flag_active=True),
        label=u"",
        widget=ModelSelect2Widget(
            model=Inventory_product_base,
            search_fields=['name__icontains'],
            attrs={'data-placeholder': 'Select product...', 'data-width': '100%'},),)

    class Meta():
        model = Inventory_unit_catalog
        fields = ('parent_product_base',)


class InventoryCatalogUpdateAllProductsForm(forms.ModelForm):
    parent_product_base = forms.ModelChoiceField(
        queryset=Inventory_product_base.objects.all(),
        label=u"",
        widget=ModelSelect2Widget(
            model=Inventory_product_base,
            search_fields=['name__icontains'],
            attrs={'data-placeholder': 'Select product...', 'data-width': '100%'},),)

    class Meta():
        model = Inventory_unit_catalog
        fields = ('parent_product_base',)

InventoryCatalogUpdateProductsFormset = modelformset_factory(model=Inventory_unit_catalog,form=InventoryCatalogUpdateProductsForm,extra=10,can_delete=True)

InventoryCatalogUpdateAllProductsFormset = modelformset_factory(model=Inventory_unit_catalog,form=InventoryCatalogUpdateAllProductsForm,extra=10,can_delete=True)

VIEW:
if product_flag == 'active':
    formset = InventoryCatalogUpdateProductsFormset(queryset=parent_unit_catalog.products.filter(flag_active=True))
else:
    formset = InventoryCatalogUpdateAllProductsFormset(queryset=parent_unit_catalog.products.all())

如前所述,如果我将上述查询集更改为.none()(或其他任何东西,无论是在小部件中还是在视图中)在select2字段中呈现的选择都没有区别。

As noted, if I change the above queryset to .none() (or anything else, either in the widget or in the view) there is no difference in the rendered choices in the select2 field.

我尝试了单独的,并行的表单和表单集。最初,我尝试一种更复杂的方法,通过添加以下内容来传递参数并在单个表单中选择不同的查询集:

I've tried separate, parallel forms and formsets. Originally I tried for a more sophisticated approach, to pass a parameter and have the different querysets selected within a single form, by adding the following:

def __init__(self, *args, **kwargs):
    self.product_flag = kwargs.pop('product_flag')
    super(InventoryCatalogAddToForm, self).__init__(*args, **kwargs)
    print("__init__ has product_flag: ",self.product_flag)
    if self.product_flag == 'active':
        self.fields['parent_product_base'].queryset = Inventory_product_base.objects.filter(flag_active=True)
        print("Screened for flag_active=True")
    else:
        self.fields['parent_product_base'].queryset = Inventory_product_base.objects.all()
        print("Screened for flag_active=False")

,我能够通过调试打印出正在执行正确的过滤器选择,但没有任何效果。因此,我转回使用一种更简单,更直接的分离形式的方法,但是仍然没有。

and I was able to verify by the debug prints that the correct filter choices were executing, but without any effect. So I moved back to a simpler, more direct approach of separate forms, and still nothing.

任何建议都将受到欢迎。我的项目已经进行了几个月,而Django-Select2是其中的基础之一,我不愿意得知它无法过滤select2的输入,因此我需要找到一个替换项。

Any advice would be welcome. My project is several months in and Django-Select2 is one of the foundations across it, I would hate to learn that it cannot filter the select2 input and I would need to find a replacement.

推荐答案

self.fields ['parent_product_base']。queryset 设置表单字段的查询集(即允许的验证选项) 。

self.fields['parent_product_base'].queryset sets the queryset for the formfield (i.e. allowed choices for validation).

使用 self.fields [’parent_product_base']。widget.queryset 设置小部件的选择。

Use self.fields['parent_product_base'].widget.queryset to set the widget's choices.

这篇关于django-select2小部件的查询集被忽略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆