Code

Opened 3 years ago

Last modified 3 years ago

#15099 new Bug

ModelFormset.queryset requirement is too strict

Reported by: Ciantic 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

Description

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)
    ...

Attachments (0)

Change History (3)

comment:1 Changed 3 years ago by russellm

  • Component changed from Uncategorized to Forms
  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Triage Stage changed from Unreviewed to Accepted

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 3 years ago by jaddison

  • Severity set to Normal
  • Type set to Bug

comment:3 Changed 3 years ago by dtrebbien

  • Cc dtrebbien added
  • Easy pickings unset
  • UI/UX unset

Add Comment

Modify Ticket

Change Properties
<Author field>
Action
as new
The owner will be changed from nobody to anonymous. Next status will be 'assigned'
as The resolution will be set. Next status will be 'closed'
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.