我试图通过CharField'名称'来尝试订购查询集,但我想排除'其他'输入并将其添加为用户选择的最后一个选项...
self.fields["acquisition"].queryset = AcquisitionChannel.objects.exclude(name = "Other").order_by('name')
上述情况显然不太好,因为它排除了其他' ...
可以在Django中完成吗?或者我必须使用Javascript?
谢谢!
答案 0 :(得分:0)
要手动将对象添加到QuerySet,请尝试_result_cache
:
other = AcquisitionChannel.objects.get(name="Other")
objs = AcquisitionChannel.objects.exclude(name="Other").order_by("name")
len(objs) #hit the db to evaluate the queryset.
objs = objs._result_cache.append(other)
self.fields["acquisition"].queryset = objs
答案 1 :(得分:0)
快速而简单:使用order
添加一个带有特殊值的extra()
列:
self.fields["acquisition"].queryset = (
AcquisitionChannel.objects
.extra(select={'order': '(CASE name WHEN %s THEN 1 ELSE 0 END)'},
select_params=['Other'],
order_by=['order', 'name']))
使用params
,此方法适用于任何数据库(支持CASE
)。
答案 2 :(得分:0)
它类似于:
def get_choices():
choices = AcquisitionChannel.objects.exclude(name = "Other").order_by('name').values_list('value_column', 'text_column')
other = AcquisitionChannel.objects.filter(name = "Other").values_list('value_column', 'text_column')
choices = list(choices)
other = list(other)
return choices + other
然后:
acquisition = forms.ChoiceField(choices=get_choices())