Django表单和查询集

Django表单和查询集

本文介绍了Django表单和查询集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我需要过滤多个选择框中可用的选项.

Lets say I need to filter the options available in a multiple select box.

我认为我有

class ArticleCheckbox(forms.ModelForm):
    article= forms.ModelMultipleChoiceField(queryset=Article.objects.all(),required=False, widget=forms.CheckboxSelectMultiple)
    class Meta:
        model = Book
        fields = ('m2m_article',)

.在我看来,我将分配:

.In my view I will assign:

articleform = ArticleCheckbox()
articleform.fields["m2m_article"].queryset = Article.objects.filter(category = "Animals")

在视图中分配查询集如何影响类(Article.object.all())中的查询集?它会覆盖吗?我不这么认为.

How does the assigning of the queryset in the view affect the queryset from classes (Article.object.all()) ?Does it overwrite? I do not think so.

我想覆盖查询集.我该怎么办?

I would like to override the queryset. How can I do it?

推荐答案

执行方法正确,只不过您分配了 class 而不是 ArticleCheckBox

The way you're doing it is correct, except for you assign the class and not an instance of ArticleCheckBox

articleform = ArticleCheckbox()

初始化表单时,将为其提供默认查询集,并且您将其覆盖,因此最初的查询集将永远不会查询数据库,因为此时无需检索任何数据.

When the form is initialised it is given a default queryset and you are overriding it, the initial one will never query the database since no data is ever needed to be retrieved at that point.

这篇关于Django表单和查询集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 05:13