2017-01-06 3 views
0

У меня проблема, когда я просматриваю поле ManyToMany на мой взгляд.Django QuerySet отображает неправильную строку

#Models:

from django.db import models 


class Ingredient(models.Model): 
    content = models.CharField(max_length=300, default='') 

    def __str__(self): 
     return self.content 


class Drink(models.Model): 
    ingredient = models.ManyToManyField(Ingredient) 
    title = models.CharField(max_length=300) 
    description = models.TextField(max_length=500) 

    def __str__(self): 
     return self.title 

#view:

from django.shortcuts import render 
from .models import Drink, Ingredient 


def index(request): 
    drinks = Drink.objects.all() 
    context = {'drinks': drinks} 
    return render(request, 'drinks/index.html', context) 

#Template:

{% for i in drinks %} 
    <h3>{{ i.title }}</h3> 
    <p><b>Description:</b> <br>{{ i.description }}</p> 
    <p>{{ i.ingredient.all }}</p> 
{% endfor %} 

Вот мой веб-сайт:

Screw driver 

Description: 
Good drink made of pure vodka and California cultured oranges. 

<QuerySet [<Ingredient: Vodka>, <Ingredient: Orange juice>]> 

Я не могу найти подходящий способ фильтрации или форматирования последней строки. Есть ли у кого есть идеи?

+2

Вы уже знаете, как перебирать «напитки». Почему бы не сделать то же самое с 'i.ingredient.all'? Они оба являются запросами. –

+0

Да, я не знаю ... Ха-ха был черным, я понятия не имею. Спасибо! – MB95

ответ

1

Вам нужно также перебирать ингредиенты.

{% for i in drinks %} 
    <h3>{{ i.title }}</h3> 
    <p><b>Description:</b> <br>{{ i.description }}</p> 
    {% for j in i.ingredient.all %} 
     <p>{{ j }}</p> 
{% endfor %} 
+0

Ах ... Конечно, так глупо от меня ... Спасибо, это все. – MB95