S
S
stayHARD2015-06-16 19:38:58
Django
stayHARD, 2015-06-16 19:38:58

How to combine two for loops?

Good evening.
I'm currently trying to get my head around Django (1.8.2).
I am writing a small semblance of an online store. Now I'm trying to display the product attribute and its value. I have them in separate tables according to EAV .
My views:

def macbook_view_by_id(request, macbook_id):
  characteristics = ItemAttribute.objects.filter(category=3)
  values = ItemAttributeValue.objects.filter(product=macbook_id)
  return render(request, 'macbook_page.html', \
    {'characteristics': characteristics,'values': values, 'nbar': 'macbook'})

After that, I want to get the characteristics in the form:
характеристика:значения
характеристика:значения
....
характеристика:значения

But of course I get this:
характеристика
характеристика
...
характеристика

and also this:
значение
значение
...
значение

In Google found one solution using zip:
{% for i, j in zipped_data %}
    {{ i }}, {{ j }}
{% endfor %}

but unfortunately it gives out not what you need (shows objects).
What to do in such cases?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan, 2015-06-16
@ATNC

you can get objects that are "bound" to your model by adding related_name.
For example:
models.py

class ItemAttributeValue(models.Model):
    att1 = .....
    att2 = .....
    item = models.ForeignKey(ItemAttribute, related_name='attribute')

views.py
index.html
{% for i in characteristics %}
{{ i.name}}
...
{{ i.attribute.att1}}
...
{% endfor %}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question