Ticket #10263: inlineformset_factory_order_by.diff
File inlineformset_factory_order_by.diff, 2.3 KB (added by , 16 years ago) |
---|
-
django-trunk/django/forms/models.py
462 462 class BaseInlineFormSet(BaseModelFormSet): 463 463 """A formset for child objects related to a parent.""" 464 464 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): 466 466 from django.db.models.fields.related import RelatedObject 467 467 if instance is None: 468 468 self.instance = self.model() … … 472 472 # is there a better way to get the object descriptor? 473 473 self.rel_name = RelatedObject(self.fk.rel.to, self.model, self.fk).get_accessor_name() 474 474 qs = self.model._default_manager.filter(**{self.fk.name: self.instance}) 475 if order_by: 476 qs = qs.order_by(order_by) 475 477 super(BaseInlineFormSet, self).__init__(data, files, prefix=prefix or self.rel_name, 476 478 queryset=qs) 477 479 … … 543 545 544 546 def inlineformset_factory(parent_model, model, form=ModelForm, 545 547 formset=BaseInlineFormSet, fk_name=None, 546 fields=None, exclude=None, 548 fields=None, exclude=None, order_by=None, 547 549 extra=3, can_order=False, can_delete=True, max_num=0, 548 550 formfield_callback=lambda f: f.formfield()): 549 551 """ … … 551 553 552 554 You must provide ``fk_name`` if ``model`` has more than one ``ForeignKey`` 553 555 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 554 561 """ 555 562 fk = _get_foreign_key(parent_model, model, fk_name=fk_name) 556 563 # enforce a max_num=1 when the foreign key to the parent model is unique. … … 573 580 'fields': fields, 574 581 'exclude': exclude, 575 582 'max_num': max_num, 583 'order_by': order_by, 576 584 } 577 585 FormSet = modelformset_factory(model, **kwargs) 578 586 FormSet.fk = fk