pynovice
pynovice

Reputation: 7752

Loop inside loop in queryset in Django template

I have queryset like this:

hello = Hello.objects.all()

In template I would do like this to get the data:

{% for h in hello %}
   {% for i in h.data %} #data is stored like this ['a', 'b', 'c'] -->  I want to access individual componenet, thus I would do:
      {{i}}
   {% endfor %}
{% endfor %}

But instead of yielding data as:

a 
b
c 

It yields as ['a', 'b', 'c']

What's wrong? I have a reason to store data in list. How to access each data seperately. Thanks

Purpose: Colors are stored in data field as: [black, green, brown] Thus I want to achieve:

div style="color: black"
div style="color: green"
div style="color: brown"

Edit models.py class Hello(models.Model): user = models.ForeignKey(User) data = models.CharField(max_length=255)

def __str__(self):
    return "%s's decoration photos" % self.user

Upvotes: 0

Views: 1107

Answers (2)

Anup
Anup

Reputation: 753

The best way to deal with this would be to write your own django template filter to iterate over the filter.

Very similar to what is given at https://docs.djangoproject.com/en/dev/ref/templates/builtins/

And getting start is here. https://docs.djangoproject.com/en/dev/howto/custom-template-tags/

Upvotes: -1

arocks
arocks

Reputation: 2882

Assuming Hello is a model with data stored as a CharField, then Django is correct in assuming that you have a string rather than a list.

Try using a model called Color which has a ForeignKey to Hello. This would be the right way to have a one-to-many relationship between Hello and its Color objects.

Upvotes: 1

Related Questions