Django ModelChoiceField使用一个模型属性中的不同值 [英] Django ModelChoiceField using distinct values from one model attribute

查看:309
本文介绍了Django ModelChoiceField使用一个模型属性中的不同值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在一个django应用程序,我有一个模型事件。每个事件都有一些属性,其中一个是主机名(我将以此作为示例)。我需要实现搜索功能,用户可以搜索具有hostname == some_value的所有事件,例如hostname ==myhost.foo.bar。



现在,我想允许用户选择有效的选项(即实际存在于一个或多个更多的事件)在搜索表单的组合框中,所以我使用ModelChoiceFields为我的窗体。 ModelChoiceView的子类,用于显示正确的标签:

  class HostnameModelChoiceField(forms.ModelChoiceField):
def label_from_instance self,obj):
return obj.host.hostname

我的表单:


 类QueryForm(forms.Form):
hostname = HostnameModelChoiceField(queryset = Event.objects.all(),required = False )
...

但是,这给了重复,因为许多事件可能有相同的主机名。我尝试在查询器上使用distinct(),但是当然这不会奏效,因为对象是不同的(即使显示的值不是)。



所以,我试图改为仅选择我需要的值:

 类QueryForm(forms.Form):
hostname = ModelChoiceField(queryset = Event.objects.all()。values_list(hostname,hostname)。distinct(),required = False)

但这不会验证!我怀疑因为这些值不是实际的事件实例,只是字符串值。



所以我尝试了一个常规的ChoiceField:

  hostname = forms.ChoiceField(choices = Event.objects.all()。values_list(hostname,hostname)。distinct(),required = False)

这是有效的,但是这个列表只能填入一次,所以它不是最新的数据库。

所以...有什么好办法解决这个问题吗?要回顾一下问题:如何使用模型的某个字段中的不同值填充组合框,并且还将其与数据库保持同步?我会认为,一个ModelChoiceField是最好的选择,如果我可以使用它来验证使用.values(...)或.values_list(...)。



真诚的,
哈吉格尔

解决方案

第二种方式将会起作用,但您需要在 init ,所以每次调用表单时刷新。



例如

 类QueryForm(forms.Form):
hostname = forms.ChoiceField(choices = [],required = False)

def __init __(self,* args,** kwargs):
super(QueryForm,self) (* args,** kwargs)
self.fields ['hostname']。choices = Event.objects.all()。values_list(hostname,hostname)。distinct()


so I'm working on a django application where I have a model Event. Each Event has some attributes, say one of them is "hostname" (which I will use throughout as an example). I need to implement search functionality where a user can search for all events that has hostname == some_value, e.g. hostname == "myhost.foo.bar".

Now, I wanted to allow the user to select among the valid options (i.e. the hostnames that actually exist in one or more event) in a combobox in the search form, so I use ModelChoiceFields for my form. My subclass of ModelChoiceView, for displaying the correct label:

class HostnameModelChoiceField(forms.ModelChoiceField):
def label_from_instance(self, obj):
    return obj.host.hostname

My form:

class QueryForm(forms.Form):
    hostname = HostnameModelChoiceField(queryset=Event.objects.all(), required=False)
    ...

However, this gives duplicates because many events may have the same hostname. I attempted using "distinct()" on the queryset but of course that won't work because the objects are distinct (even if the displayed values are not).

So, I tried to instead select only the values I need:

class QueryForm(forms.Form):
    hostname = ModelChoiceField(queryset=Event.objects.all().values_list("hostname", "hostname").distinct(), required=False)

But this won't validate! I suspect because the values are not actual Event instances but just string values.

So I tried a regular ChoiceField:

hostname = forms.ChoiceField(choices=Event.objects.all().values_list("hostname", "hostname").distinct(), required=False)

This works, BUT this list is only populated once, so it's not up to date with the database.

So... Is there any good way of solving this problem? To recap the question: HOW do I populate a combo box with the distinct values from one of the fields of a model, and also keeping it in-sync with the database? I would think that a ModelChoiceField would be the best bet, if I can get it to validate when using .values(...) or .values_list(...).

Sincerely, Hallgeir

解决方案

The second way will work, but you need to set the choices on init so its refreshed each time the form is called.

e.g

class QueryForm(forms.Form):
    hostname = forms.ChoiceField(choices=[], required=False)

    def __init__(self, *args, **kwargs):
        super(QueryForm, self).__init__(*args, **kwargs)
        self.fields['hostname'].choices = Event.objects.all().values_list("hostname","hostname").distinct()

这篇关于Django ModelChoiceField使用一个模型属性中的不同值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆