简体   繁体   中英

Django modelformset order_by not working

I want to use a Django (1.4) modelformset in which, when the formset is loaded the forms will be arranged by a exam_date field I have in my model. To do this I've created the following simple BaseModelFormSet

class BaseExamDateFormSet(BaseModelFormSet):
    def __init__(self, *args, **kwargs):
        super(BaseExamDateFormSet, self).__init__(*args, **kwargs)
        self.queryset = models.ExamDate.objects.all().order_by('exam_date')

As you can see I've changed the queryset as proposed in the django docs (later I'll also change its clean method but it doesn't matter right now). After that I am using it in my view to create the formset:

ExamDateFormSet = modelformset_factory(
    models.ExamDate, 
    exclude =('authority', ), 
    can_delete=True, 
    extra=1,
    formset = forms.BaseExamDateFormSet
)
...
formset = ExamDateFormSet()

My problem is that when the formset is rendered the data in the forms is always in the same ordering (probaby by id) regardless of the value of the order_by attribute :(

Should I try setting a default order by in my ExamDate model ? I really don't like that solution though :(

TIA !

After some more searching I found a solution !

I ignored the queryset attribute and added the following method to the BaseExamDateFormSet:

def get_queryset(self):
    return models.ExamDate.objects.all().order_by('exam_date')

However I don't know yet why the queryset attribute isn't working.

更简单的是,在上述代码中,您可以在modelformset_factory调用中擦除formset =参数,并将实例集实例化为:

formset = ExamDateFormSet(queryset=models.ExamDate.objects.order_by('exam_date'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM