Ticket #10263: inlineformset_factory_order_by.diff

File inlineformset_factory_order_by.diff, 2.3 KB (added by Paulo Scardine <paulo@…>, 7 years ago)

Patch to add order_by parameter for inlineformset_factory

  • django-trunk/django/forms/models.py

     
    462462class BaseInlineFormSet(BaseModelFormSet):
    463463    """A formset for child objects related to a parent."""
    464464    def __init__(self, data=None, files=None, instance=None,
    465                  save_as_new=False, prefix=None):
     465                 save_as_new=False, prefix=None, order_by=None):
    466466        from django.db.models.fields.related import RelatedObject
    467467        if instance is None:
    468468            self.instance = self.model()
     
    472472        # is there a better way to get the object descriptor?
    473473        self.rel_name = RelatedObject(self.fk.rel.to, self.model, self.fk).get_accessor_name()
    474474        qs = self.model._default_manager.filter(**{self.fk.name: self.instance})
     475        if order_by:
     476            qs = qs.order_by(order_by)
    475477        super(BaseInlineFormSet, self).__init__(data, files, prefix=prefix or self.rel_name,
    476478                                                queryset=qs)
    477479
     
    543545
    544546def inlineformset_factory(parent_model, model, form=ModelForm,
    545547                          formset=BaseInlineFormSet, fk_name=None,
    546                           fields=None, exclude=None,
     548                          fields=None, exclude=None, order_by=None,
    547549                          extra=3, can_order=False, can_delete=True, max_num=0,
    548550                          formfield_callback=lambda f: f.formfield()):
    549551    """
     
    551553
    552554    You must provide ``fk_name`` if ``model`` has more than one ``ForeignKey``
    553555    to ``parent_model``.
     556
     557    Optional parameter order_by chains an order_by filter to the resulting
     558    ``InlineFormSet`` queryset. This avoids some unpleasant reordering effects when using
     559    PRG (Post/Redirect/Get) with some database engines. Example: order_by='-pub_date'
     560
    554561    """
    555562    fk = _get_foreign_key(parent_model, model, fk_name=fk_name)
    556563    # enforce a max_num=1 when the foreign key to the parent model is unique.
     
    573580        'fields': fields,
    574581        'exclude': exclude,
    575582        'max_num': max_num,
     583        'order_by': order_by,
    576584    }
    577585    FormSet = modelformset_factory(model, **kwargs)
    578586    FormSet.fk = fk
Back to Top