Thursday, December 7, 2017

Sending multiple primary keys to view in django

I recently faced a problem where I have to handle two different models in same view function. To do that I had to pass multiple primary keys of multiple models to view. I solved the problem in following way:

First in the template file, I called the view in following way
I had already defined two models named Model1 and Model2.

<a href = "{% url 'app:view_function' pk=model1.pk pk_alt=model2.pk %}">Link</a>
 
Then in my views.py file I wrote the view_function function as below

def view_function(request, pk, pk_alt):
        Model1_object = get_object_or_404(Model1, pk=pk)
        Model2_object =get_object_or_404(Model2, pk=pk_alt)
        # handle other task
 
The last thing is handling url routing carefully. In urls.py file you have to write url routing as below

url(r'^urlName/(?P<pk>\d+)/(?P<pk_alt>\d+)/$', views.view_function,name='view_function')

No comments:

Post a Comment