janlinhart567
janlinhart567

Reputation: 11

What is 'instance=' and 'queryset=' in django?

what does it do in this function, what does it mean generally?

def createOrder(request, pk):
        OrderFormSet = inlineformset_factory(Customer, Order, fields = ('product','status'), extra=10)
        customer=Customer.objects.get(id=pk)
        formset=OrderFormSet(queryset=Order.objects.none(),instance=customer)
        
        if request.method=='POST':
            
            formset=OrderFormSet(request.POST,instance=customer)
            if formset.is_valid():
                formset.save()
                return redirect('/')
        context={'formset':formset}
        return render(request, 'accounts/order_form2.html',context)

Upvotes: 0

Views: 637

Answers (1)

D Malan
D Malan

Reputation: 11424

inlineformset_factory creates a formset for model objects that belong to a certain other model object. The first argument is parent_model which is the class of the "parent" model (the one to which the others must belong). The second argument is model - the model class for which the forms will be created.

With inlineformset_factory(Customer, Order,... you are creating a formset that can create forms for Orders that belong to a certain Customer.

The way you can specify which specific Customer all the Orders must belong to is by passing the instance argument to the formset. An example is given under Inline formsets in the docs.

The queryset argument allows you to limit for which objects in the model to create a form for. In your case, for which Orders a form should be displayed. An example is given under Changing the queryset in the docs. By default queryset is set to all of the objects in the model, e.g. Order.objects.all().

Order.objects.none() selects an empty queryset. Setting queryset to an empty queryset will mean that no forms will be displayed for existing Orders. Only a form for a new Order will be displayed.

With OrderFormSet(queryset=Order.objects.none(),instance=customer) like you have above, you're essentially saying: create a form for a new Order object which should be linked to customer.

Upvotes: 1

Related Questions