6
\$\begingroup\$

Can I make my template syntax simpler? I'm hoping to eliminate the if and maybe also the for block.

This worked in the shell but I can't figure out the template syntax.

recipes[0].recipephotos_set.get(type=3).url

model.py

class Recipe(models.Model):
 ....
class RecipePhotos(models.Model):
 PHOTO_TYPES = (
 ('3', 'Sub Featured Photo: 278x209'),
 ('2', 'Featured Photo: 605x317'),
 ('1', 'Recipe Photo 500x358'),
 )
 recipe = models.ForeignKey(Recipe)
 url = models.URLField(max_length=128,verify_exists=True)
 type = models.CharField("Type", max_length=1, choices=PHOTO_TYPES)

view.py

recipes = Recipe.objects.filter(recipephotos__type=3)

template.html

{% for recipe in recipes %}
 {% for i in recipe.recipephotos_set.all %} 
 {% if i.type == '3' %}
 {{ i.url }}
 {% endif %}
 {% endfor %}
 <a href="/recipe/{{ recipe.recipe_slug }}/">{{ recipe.recipe_name }}</a></li>
{% empty %}
Peilonrayz
44.4k7 gold badges80 silver badges157 bronze badges
asked Jan 30, 2011 at 1:57
\$\endgroup\$

1 Answer 1

9
\$\begingroup\$

I'll refer you to a Stack Overflow post that pretty much nails the answer.

I assume that you want to display all recipes that have "Sub Featured Photos".

The call recipes = Recipe.objects.filter(recipephotos__type=3) will give you a queryset of recipes that have at least one photos with type 3. So far so good. Note, that this code is in the views.py file and not in the template. Like the StackOverflow post mentioned, you should put the filtering code in your view or model.

Personally I'd prefer writing a function for your model class:

class Recipe(models.Model):
 (...)
 def get_subfeature_photos(self):
 return self.recipephotos_set.filter(type="3")

And access it in the template like this:

{% for recipe in recipes %}
 {% for photo in recipe.get_subfeature_photos %}
 {{ photo.url }}
 {% endfor %}
 (...)
{% endfor %}

Please note that the function is using filter() for multiple items instead of get(), which only ever returns one item and throws a MultipleObjectsReturned exception if there are more.

answered Jan 30, 2011 at 8:06
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.