Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing query set object in django template

Tags:

I have two models, named as Human and Animal. The primary key of Human is foreign key in the Animal model. Both has 3 columns each. Human model has c, e, r columns. Animal model has l, i, p columns. I am running a django query on Human model, like this.

result = Human.objects.filter().order_by('r') 

result is an queryset object. This object is sent from my view file to a django template page. Inside template page I am looping through result and displaying the column values.

Now what i want to do is, I want to also fetch value of p column(which is present in the Animal model) inside the same loop, inside that django template. How can we do it in the django template page.

In the python file I can do like this

for i in result:     print i.animal_set.values()[0]['p'] 

But I want to do it in the template page.

like image 262
sandeep Avatar asked Jan 14 '13 15:01

sandeep


People also ask

What is Django query set?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.

What is __ GTE in Django?

The __lte lookup [Django-doc] means that you constrain the field that is should be less than or equal to the given value, whereas the __gte lookup [Django-doc] means that the field is greater than or equal to the given value.

What does {% %} mean in Django?

{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.


1 Answers

{% for record in result %}     {{record.c}}, {{record.e}},      {% for animal in record.animal_set|slice:":1" %}         {{animal.p}}     {% endfor %} {% endfor %} 
like image 108
Aamir Rind Avatar answered Sep 29 '22 12:09

Aamir Rind