Django 1.10 - 从单个queryobject创建两个formset

时间:2017-04-12 15:00:58

标签: django django-forms django-queryset

我有Book模型,其中包含titleauthor字符串字段。 title字段可能不同,但author始终等于joeymartin

在一个页面上,我想显示两个formsets,但我不想创建QuerySet并为每个表单单独进行数据库查询。是否可以一次获取所有对象,然后将它们拆分为单独的lists并将它们传递给formset

我的观看功能:

def index(request):

    books = Book.objects.all()  # Here we will take all at once

    joey_books = []
    martin_books = []

    for book in books:  # books here are evaluated - only once!
        if book.author == 'joey':
             joey_books.push(book)
        elif book.author == 'martin':
             martin_books.push(book)

    joey_book_formset = forms.modelformset_factory(
        Book,
        form=BookForm,
        fields=['title', 'author'],
        can_delete=True, extra=1
    )

    joey_book_formset = joey_book_formset(queryset=joey_books)  # Exception raised

    martin_book_formset = forms.modelformset_factory(
        Book,
        form=BookForm,
        fields=['title', 'author'],
        can_delete=True, extra=1
    )

    martin_book_formset = martin_book_formset(queryset=martin_books)  # Exception raised

    context = {
        'joey_forms': joey_book_formset,
        'martin_forms': martin_book_formset,
    }

    return render(request, 'myapp/index.html', context)

我的期望:

将创建两个表单集,并且只运行一个查询。

问题

引发exception之后:

  

AttributeError:' list'对象没有属性' ordered'

可能是因为formsets只接受QuerySet个对象。这有什么解决方法吗?想象一下,我在单页上有50个表单。我不想为每个表单集运行50个单独的查询。

0 个答案:

没有答案