Django - iterate through 2 objects synchronously in the template form - django

How do I iterate through 2 objects synchronously in the template form?
I have 2 objects in my views; one object is products, the other prices. Both are lists.
I want to cycle through both products and prices at the same time in the templates form.
Usually in python I would just make a simple while loop as such:
n = 0
while n < len(products):
print products[n], prices[n]
n+=1
I haven't found anything similar in the templates form yet.
Any help would be appreciated.

You could write a custom template filter to get the nth item in the list, but this is what I would do:
Zip the 2 lists together in the view:
products_prices = zip(products, prices)
Then loop through that looped list in the template:
{% for product, prices in products_prices %}
{{ product }}, {{ price }}
{% endfor %}

You might want to use forloop.counter, docs at https://docs.djangoproject.com/en/dev/ref/templates/builtins/

The built in template tags don't have an easy way to do this that I can recall. The simplest approach will be to zip the two lists together in your view, then provide the zipped data structure in the context. You could also write a custom zip template tag, if you're feeling adventurous.

Related

Length of list in jinja template, where the list is the result of a DBSession.query

How do I find the length of a list of objects in a jinja template when the list of objects has been created by querying a database?
I thought There are {{ items|length }} items in this category. would work, but items is a result of:
items = db_session.query(Item).filter_by(category_id=category.id)
and I get the error
TypeError: object of type 'Query' has no len()
Obviously, I could calculate the length separately and pass into render_template(), but I wondered if there was a better way?
Any help from the community would be much appreciated :)
items object is not a list yet, it is an unprocessed Query object as you see in the error. You can use Query.all() method to get a list of items:
items = db_session.query(Item).filter_by(category_id=category.id).all()
After that length filter can be applicable.
Use {{ items | count }} in jinja template
Try to add loopcontrol extension
app.jinja_env.add_extension('jinja2.ext.loopcontrols')
Then
{% for item in items %}
{{loop.length}}
{% break %}
{% endfor %}

Flask-SQLAlchemy number of results in query

I was wondering if anyone knows how to output the number of results from a query in a flask template.
Example view code:
products = Product.query.all()
In the template it would be handy to be able to just do:
{{ products.count() }}
Is there anyway to do this already, or does anyone have a filter written that does this?
Cheers,
Your products template variable is a regular list. You can use the length filter to gets its size:
{{ products|length }}
But if you are working with paginated results then this will give you the size of one page. If you want the size of the entire query then you have to call count() on the query object. For example:
product_count = Product.query.count()
Then pass this to the template as an additional argument. Or if you prefer you can pass the query object to the template and call count() from there:
{{ product_query.count() }}
you can use len(products) ,
it is standart python function and works for me

Issues with Fetching the data from database

I can fetch the data like this.
value= mymodel.objects.get(anycondition)
OR
value= mymodel.objects.filter(anycondition)
and can send them to my template with context.
But if I want to select all the data from a table(for all users not only one) as this query does
value= mymodel.objects.all()
and send this value to my template and can see there field by field
e.g.
my table has two fields name and phone no and I use the above query( value= mymodel.objects.all()) now if i want to see all names then i can see that and if i want to see phone no. I can see that too.
I have tried this and it doesn't work and I even I do not know it is possible or not.
If it is possible then please let me know how I can do this ?
I hope you understand my question. !!
Thanks in advance
.all() will return a list of objects that represent the rows in your model. .get() only returns one object. Your template is trying to print the result of all() if it was one object.
This is the same as if you had a list and you wanted to loop through it. In your view you would do:
product = Product_attributes.objects.all()
for i in product:
print i.size
print i.color
The equvalent for the template is:
<ul>
{% for i in product %}
<li>{{ i.size }}</li>
<li>{{ i.color }}</li>
{% endfor %}
</ul>
Although this question isn't clear it seems like you are having a bit of problem with Field Lookups. It is fairly easy to learn Here is a link to get you started

Whats the difference between QuerySet , Tuple , Dictionary in Django template

I am having trouble in understanding how to iterate over QuerySet , Tuple and Dictionarty in django.
I am confused which djnago functions returns what like objects.all or objects.get
Suppose i have
a = model.objects.all()
b = model.object.get(pk=1)
c = Blog.objects.values('name', 'entry__headline')
d = Entry.objects.values_list('id', 'headline')
e = Person.objects.raw('SELECT * FROM myapp_person')
What is the retured in each scenario and the biggest problem is how can i iterate over.
All these confuse me very much . I studies the docs but they tell one thing and don't tell how to use in template. I know its related to python but then python don't have template to deal with
QuerySet: A Django class that processes SQL responses and returns a python construct representing the results. Although it functions like a list in many ways, it's actually what's called an "iterable". It simply mocks the behavior of a list to allow you to use things like for-loops on it.
Tuple: An immutable list. That means that once it's set, it can't be altered. In virtually every other way it behaves just like a list.
Dictionary: Also known as a hash in other languages. It can be considered a "keyed list". A "list" in the strictest of senses is a group of items stored serially in memory. In the old days of programming, you'd have to "pop" items off and "push" items onto a list, and they could only be retrieved in a FIFO, or first-in-first-out fashion. Dictionaries provide a way to "lookup" items in a list. It is composed of key-value pairs, so you can reference a key and get the attached value.
Now in terms of Django templates:
QuerySets: You iterate over these using the standard methods. Once you get a result from something like MyModel.objects.all(), you can use a {% for value in queryset %} tag.
Tuples: As far as iteration goes, these behave exactly as standard lists. You can also just simply use a {% for value in tuple %} tag. The only potential hangup is that sometimes you'll end up with tuples of tuples or a list of tuples. These are just like multi-level lists. You have to iterate over the outer list or tuple and then iterate over the inner ones.
Dictionaries: These are probably the most complicated, only because they require a method call to get an iterable object.
mydict.iteritems() # returns an iterable consisting of `(key, value)` tuples.
mydict.iterkeys() # returns an iterable consisting of the keys. You can then use mydict[key] to get the values
mydict.itervalues() # returns an iterable consisting of the values.
The last method is probably the best of simple iteration in a Django template:
{% for value in mydict.itervalues %}
Are you referring to these docs? https://docs.djangoproject.com/en/dev/ref/templates/builtins/#for
I think that's what you were looking for.
Basically you iterate over them like:
{% for item in a %}
{{item.field}}
{{item.field2}}
{% endfor %}
{{b.field}}
{% for item in c %}
{{item.name}}
{{item.entry__headline}}
{% endfor %}
{% for item in d %}
{{item}}
{% endfor %}
# Also you can do this if you want to access just a particular index:
{{d.0}}
{{d.1}}
{% for item in e %}
{{item.field}}
{{item.field2}}
{% endfor %}
As for your data types:
a would be a QuerySet or list of model objects
b would be a model object
c would be a ValuesQuerySet or a list of dictionaries
d would also be a ValuesQuerySet but it's actually a list of tuples
e would be a RawQuerySet, which acts like a normal QuerySet
Sources:
https://docs.djangoproject.com/en/dev/topics/db/sql/#django.db.models.Manager.raw
https://docs.djangoproject.com/en/dev/ref/models/querysets/#values
https://docs.djangoproject.com/en/dev/ref/models/querysets/#values-list

Django: optimizing queries

I want to list the number of items for each list. How can I find this number in a single query, rather than a query for each list?
Here is a simplified version of my current template code:
{% for list in lists %}
<li>
{{ listname }}:
{% with list.num_items as item_count %}
{{ item_count }} item{{ item_count|pluralize }}
{% endwith %}
</li>
{% endfor %}
lists is passed as: List.objects.filter(user=user)
and num_items is a property of the List model:
def _get_num_items(self):
return self.item_set.filter(archived=False).count()
num_items = property(_get_num_items)
This queries SELECT COUNT(*) FROM "my_app_item" WHERE... n times, where n is the number of lists. Is it possible to make a single query here?
You should do this in your view and send the dictionary, instead.
Model.objects.values_list('item').annotate(Count('num_items'))
This will produce the SQL same as, (or equivalent to) the one you have posted.
In the following, I tried to take into account all your constraints: filtering on fields of List, on fields of Item, counting items , and grouping by list.
The solution I see is that you could use values() (here is the django doc about this : http://docs.djangoproject.com/en/dev/topics/db/aggregation/#values)
from django.db.models import Count
lists = list(List.objects.filter(user=user))
items=Item.objects.values(list).filter(archived=False,list__in=lists).annotate(count=Count("id"))
#you will get a list of dicts of the form [{'count':2,'list':5},...] where 5 is the id of the list
#now, you can match you list with you item counts in python
list_items_count_dict={}
for item in items:
list_items_count_dict[item['list']]=item['count']
for list in lists :
list.item_count = list_items_count_dict.get(list.id)
That will make only 2 queries, one for getting the lists, the other for computing the item counts. Afterwards, you will have two loops (that could probably be replaced by list comprehension one-liners ), but only for the lists you are interested in.
afterwards, in your template, you can use
{{list.item_count}}
There might be a more elegant option, but that is what I have found right now. I am also certain that you could reduce the number of query to one by using custom sql.
Disclaimer: I have not tested this code, but I have tested similar code on similar models. You could have problems because list is one of the keyword of the Python language.