开发者

Django Distinct on queryset in forms.py

开发者 https://www.devze.com 2022-12-25 15:43 出处:网络
I try to get a list with distinct into the forms.py like this: forms.ModelMultipleChoiceField(queryset=Events.objects.values(\'hostname\'), required=False).distinct()

I try to get a list with distinct into the forms.py like this:

forms.ModelMultipleChoiceField(queryset=Events.objects.values('hostname'), required=False).distinct()

In the python shell this command works perfect, but when trying it in forms.py leaves me a blank form, so nothing appears. When i just do Events.objects.all() the form appears, but distinct doesn't work with Events.objects.all()... i also tried values_list etc but doesn't seem to fit into the forms neither... anyone got an idea how to get a SELECT DISTINCT into a ModelMultipleChoiceField?

I read some other questions 开发者_如何学JAVAabout this at stackoverflow but nothing seems to work out with me, so hopefully someone knows how to do this in forms.py.

Thxs in advance


For a ModelMultipleChoiceField, Django expects a model object - because it stores the value of the selected item's primary key. In other words, it's meant to be used to manage ManyToMany fields.

It sounds like you're wanting to store the actual string value, so this might not be the right choice for you. You probably want to use a standard MultipleChoiceField, and override the form's __init__ method to set the field's choices attribute. Remember though that any choice field is a set of 2-tuples, each containing the db value and the display value - so even though you want them to be the same, you'll need to include the value twice:

def __init__(self, *args, **kwargs):
    super(MyFormClass, self).__init__(*args, **kwargs)
    self.fields['mychoicefield'].choices = [(x[0], x[0]) for x in
                               Event.objects.values_list('hostname').distinct()])
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号