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.
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.
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.
{% %} 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.
{% for record in result %} {{record.c}}, {{record.e}}, {% for animal in record.animal_set|slice:":1" %} {{animal.p}} {% endfor %} {% endfor %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With