[英]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. 我想使用Django(1.4)modelformset,在该模型中,加载表单集时,表单将由模型中的exam_date字段进行排列。 To do this I've created the following simple BaseModelFormSet
为此,我创建了以下简单的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). 如您所见,我已经按照django文档中的建议更改了查询集(稍后,我还将更改其clean方法,但现在没有关系)。 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 :( 我的问题是,在呈现表单集时,无论order_by属性的值如何,表单中的数据始终以相同的顺序排列(按id排序):(
Should I try setting a default order by in my ExamDate model ? 我应该尝试在ExamDate模型中通过设置默认订单吗? I really don't like that solution though :(
我真的不喜欢这种解决方案:(
TIA ! TIA!
After some more searching I found a solution ! 经过更多搜索后,我找到了解决方案!
I ignored the queryset attribute and added the following method to the BaseExamDateFormSet: 我忽略了queryset属性,并将以下方法添加到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. 但是我还不知道为什么queryset属性不起作用。
更简单的是,在上述代码中,您可以在modelformset_factory调用中擦除formset =参数,并将实例集实例化为:
formset = ExamDateFormSet(queryset=models.ExamDate.objects.order_by('exam_date'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.