Tomasz Brzezina
Tomasz Brzezina

Reputation: 1534

forms.modelform ordering?

class OperationCategoryOnlyForm(forms.ModelForm):
    class Meta:
      model = Operation
      fields = ('operation_type', 'category', 'related_account', )
      ordering = ['date']


OperationFormSet = modelformset_factory(Operation, form=OperationCategoryOnlyForm)

this is very easy question - why it doesn't work, and what to do to get it sorted different than default (by id)

Upvotes: 0

Views: 173

Answers (1)

Alasdair
Alasdair

Reputation: 308949

ordering is not a valid option for a model form's Meta class, so specifying it won't do anything.

If you always want to order the model by a particular field, you can simply set ordering in the model's Meta class. This will affect the ordering in other places e.g. in the django admin.

class Operation(models.Model):
    # field definitions
    class Meta:
        ordering = ('date',)

If you only want to change the ordering for this formset, provide a custom queryset when you initialize it.

OperationFormSet = modelformset_factory(Operation, form=OperationCategoryOnlyForm, queryset=Operation.objects.order_by('date'))

Upvotes: 1

Related Questions