Opened 6 years ago

Last modified 5 years ago

#15099 new Bug

ModelFormset.queryset requirement is too strict

Reported by: Jari Pennanen Owned by: nobody
Component: Forms Version: 1.2
Severity: Normal Keywords:
Cc: dtrebbien Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


Why is the ModelFormset requiring QuerySet? With very few modifications to BaseModelFormset it could be sequence, list or RawQuerySet.

In my specific use case I needed to use RawQuerySet in the ModelFormset, following workaround works for RawQuerySets and lists of objects:

def edit_users(request):
    class FakeQuerySet(list):
        def __init__(self, seq):
            super(FakeQuerySet, self).__init__(seq)
            self.ordered = True
            self.db = hasattr(seq, 'db') and seq.db or seq[0]._state.db

    users = FakeQuerySet(User.objects.raw('SELECT * FROM auth_user')) # Test with RawQuerySet
    #users = FakeQuerySet(list(User.objects.raw('SELECT * FROM auth_user'))) # Test with list

    UserFormset = modelformset_factory(User, extra=3)
    userforms = UserFormset(data=request.POST or None, queryset=users)

Change History (3)

comment:1 Changed 6 years ago by Russell Keith-Magee

Component: UncategorizedForms
Needs documentation: unset
Needs tests: unset
Patch needs improvement: unset
Triage Stage: UnreviewedAccepted

On principle, no objection here. Of course, the devil is in the detail -- especially around the implicit preconditions that querysets satisfy that a list may not necessarily satisfy (such as guaranteed ordering).

This would also be a good exercise in abstraction, separating the "list-like" bits of formsets from the queryset-specific bits.

comment:2 Changed 6 years ago by James Addison

Severity: Normal
Type: Bug

comment:3 Changed 5 years ago by dtrebbien

Cc: dtrebbien added
Easy pickings: unset
UI/UX: unset
Note: See TracTickets for help on using tickets.
Back to Top