prefetch_related display ManyToManyField values

if we have Pizza Toppings and Restaurant example from
Django Docs
. I wonder if I query the Pizza like the example:
t = Restaurant.objects.prefetch_related('pizzas__toppings')
how to extract the values of toppings for each Pizza. this should work:

b = t.pizza
d = b.topping

however, it does not work for me.
I have:

class Exercise(models.Model):
    name = models.CharField(max_length=64)
    image = models.ImageField(upload_to=content_file_name)
    
    class Meta:
        default_related_name="exercises"

    def __str__(self):
        return self.name

class Formula(models.Model):
    reps = models.PositiveSmallIntegerField(blank = True, default=0) 
    sets = models.PositiveSmallIntegerField(blank = True, default=1)
    secs = models.PositiveSmallIntegerField(blank = True, default=0)
    exercises = models.ManyToManyField(Exercise)

    class Meta:
        default_related_name="formulas"

    def __str__(self):
        return f'{self.exercises} is {self.sets} sets, {self.reps} reps, or {self.secs} seconds.'

class Day(models.Model):
    day_number = models.PositiveSmallIntegerField()
    plan = models.ManyToManyField(Plan)
    formulas = models.ManyToManyField(Formula)
    muscles = models.ManyToManyField(Muscle)

and my QuerySet is:

    today_workout = Day.objects.prefetch_related(
        'plan',
        'formulas__exercises',
        'muscles',
    ).filter(day_number=day)

I have not been successful in catching the exercise name and image from today_workout

any idea what am I doing wrong?!

silly idea but have you tried:

today_workout = Day.objects.prefetch_related(
        'plan',
        'formulas',
        'formulas__exercises',
        'muscles',
    ).**get**(day_number=day)

wondering this as you are after a single object and not a queryset “list” – maybe?

I am after a list. and the query set does work perfectly well. I have all the data I can see from the django debugging toolkit, but I don’t know how to show it in my view. I think I just came up with an idea like this:

    exercises = list()
    for exf in formulas:
        exercises.append(exf.exercises.all())  

looks silly, but I can see my exercise names
the problem is I cannot access the third table Exercises’ fields from here like:
exf.exercises.name or exf.exercises.image

Oh ok :slight_smile: - in your view or in your template?
iirc, in the template, one has to use smth like:

<ul>
{% for item in main_object.something.items.all %}
  <li>{{ item.label }}</li>
{% endfor %}
</ul>

If I may, casting the queryset into a list might be risky if your queryset is large(ish) (hence, not paginated, etc, etc?) - you may have something quite large there, depending on the circumstances.

may you please clarify what something is here?
how would it be for my QuerySet?

{% for exf in formula.exercises.all %}
 <p>{{ exf.name }}</p>