Django自动完成光

时间:2017-06-04 14:04:02

标签: django django-models autocomplete django-forms django-views

model.py:

class ReservationForm(ModelForm):

    class Meta:
        model = Reservation
        fields = '__all__'
        widgets = {
            'company': autocomplete.ModelSelect2()
    }

form.py。

class GuestContactAutocomplete(autocomplete.Select2QuerySetView):
    def get_queryset(self):

        qs = GuestContact.objects.all()

        if self.q:
            qs = qs.filter(name__istartswith=self.q)

        return qs

views.py

 public partial class MainWindow : Window {
     public MainWindow() {
         InitializeComponent();

         string hostName = Dns.GetHostName(); // Retrive the Name of HOST
                                              // Get the IP
         NetworkModel model = new NetworkModel();
         string IPv4 = String.Empty;

         // IPv4
         model.IPAddress = Dns.GetHostByName(hostName).AddressList[0].ToString();
         model.HostName = Dns.GetHostName();
         model.IPv4 = System.Net.Sockets.AddressFamily.InterNetwork.ToString();
         model.IPv6 = System.Net.Sockets.AddressFamily.InterNetworkV6.ToString();

         DataContext = model;
    }
}

我如何添加到自动填充查询集只是不空#34;公司"场? 你能救我吗?

2 个答案:

答案 0 :(得分:0)

您的公司字段是必需的,因此我认为您不会有空值。无论如何,你可以通过这个完成你想做的事情:

GuestContact.objects.exclude(company__isnull=True).exclude(company__exact='')

基本上,它的作用是从querset中排除null''值。

希望它有所帮助。

答案 1 :(得分:0)

尝试使用return qs.exclude(company='').exclude(company__isnull=True)代替return qs

更重要的是,您可能希望qs = qs.filter(company__istartswith=self.q)代替qs = qs.filter(name__istartswith=self.q)(基于forms.py

所以我认为你的views.py代码应该是:

class GuestContactAutocomplete(autocomplete.Select2QuerySetView):
    def get_queryset(self):

        qs = GuestContact.objects.all()

        if self.q:
            qs = qs.filter(company__istartswith=self.q)

        return qs.exclude(company='').exclude(company__isnull=True)