How to stop loading by default the records of a form with a foreign key type field in django?

0

I have a SALES form with a field of type foreign key of CUSTOMER, and I have converted it into a search engine that field on the client side, but django by default it loads all the existing records of the clients in a SELECT , and if there were for example about 10 thousand records of CLIENTS I will have serious problems in loading data, so I require that I do not bring any CLIENT records by default, it simply has to be activated when I search or request via AJAX. How to avoid loading those records by DEFECT, I am working with forms.ModelForm NOTE: my CUSTOMER search via AJAX already works and I am working with Select2, I enclose a search engine capture.  

Some details of form and views:

  

SALES form extract:

class VentaForm(forms.ModelForm):
class Meta:
    model = Venta
    exclude = ()
    widgets = {
       .....
        'cliente': forms.Select(attrs={'class': 'form-control'}),
  

Extract of views where I send to render the Sales Form

    @login_required
def formventas(request):
    if request.method == "POST":
        ........
    else:
        formVenta = VentaForm()
    return render(request, "tienda/venta.html", {'formVenta': formVenta})

Thanks

    
asked by Alex Ancco Cahuana 30.04.2017 в 19:05
source

1 answer

1

The fastest thing is: if you do not want to use a field, do not use it .

There are several ways to achieve this, but I think the simplest one is to exclude it from the list of fields in your model.

class VentaForm(forms.ModelForm):
    class Meta:
        model = Venta
        exclude = ['cliente', ]

All you have to do is make sure you send the client object to the save() method, for example, by making the query and saving the result instead of the value of the form:

    if form.is_valid():
        obj = form.save(commit=False)
        obj.cliente =  Cliente.objects.get(pk=request.POST['cliente'])
  

Note

     

Thanks to Alejandro Hurtado for comment the correct way to save the object Cliente .

    
answered by 30.04.2017 / 20:06
source