2013-09-24 45 views
0

我试图通过CharField“名称”来订购查询集,但我想排除“其他”条目并将其添加为用户选择的最后一个选项。 ..将特定条目添加到Queryset的末尾

self.fields["acquisition"].queryset = AcquisitionChannel.objects.exclude(name = "Other").order_by('name') 

以上,显然不是一件好事,因为它排除了“其他” ...

难道是在Django做了什么?或者我必须使用Javascript?

谢谢!

回答

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 
+0

当我调试它看起来像查询集有所有的项目,但在浏览器中的“其他”缺少。我不知道为什么... – TidharPeer

+0

添加此:objs = objs._result_cache.append(其他) - 更新我的代码以反映。 –

+0

我已经试过这个了...这会将目标更改为无 – TidharPeer

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)。

+0

没有工作...并且无论如何我不想强迫自己或其他任何人使用特定的DB ...感谢尝试 – TidharPeer

+0

它工作正常这里相当不错。它显示了错误消息还是什么? –

+0

数据库错误 - “其他”列不存在 – TidharPeer

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()) 
+0

这种类型的所有选项 - 包括“其他”,到了最后并没有把它.. – TidharPeer

+0

是,这是行不通的。如何ChoiceField和设置选择一些values_list,然后你可以追加。 – metaphy

+0

但是,它不会来自数据库...所以如果下周将添加一个新值,选择字段将不会更新 – TidharPeer