Monday, February 29, 2016

Re: Absolute beginner question -- recipes


On Mon, Feb 29, 2016 at 5:57 AM, Simon Gunacker <simon.gunacker@gmail.com> wrote:
Thank you Florian. After James pointed out that I can access my steps (and the ingredients in some way) by just passing the recipe object to the templates context, I thought of reducing the view to a DetailView again. But I have to somehow access the ingredients from my template for now ...


The related models using a 'through' table also have access to the 'through' table itself. With your current setup, I think you can do this:

<ul>
{% for steping in step.stepingredient_set.all %}
    <li>{{ steping.amount }} {{ steping.unit }} - {{ steping.ingredient }}</li>
{% empty %}
    <li>No ingredients needed for this step.</li>
{% endfor %}
</ul>

Optionally, for style points (and better human readability of the code), you can also add a 'related_name' parameter to the FK's in the 'through' table:

    step = models.ForeignKey(Step, null=True, related_name='step_ingredients')
    ingredient = models.ForeignKey(Ingredient, null=True, related_name='ingredient_steps')

That way, depending on the direction you are going, the call makes sense to a human:

<ul>
{% for steping in step.step_ingredients.all %}
    <li>{{ steping.amount }} {{ steping.unit }} - {{ steping.ingredient }}</li>
{% empty %}
    <li>No ingredients needed for this step.</li>
{% endfor %}
</ul>

I think that will work, although I haven't exactly tested this.

I'd highly recommend going with DetailView if you can. That makes your view a whopping 2 or 3 lines.

-James

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CA%2Be%2BciWYj42TNJ4KeF4vFS6_wi0cghdCee%2Bu-_QJ0VP2uzyg-Q%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment