如何使用对象的多对多关系?

时间:2019-01-29 18:36:15

标签: django

我正在使用Django 2.1

我有两个models关系ManyToMany

class Ingrediente(models.Model):
produtor = models.ForeignKey('auth.User', on_delete=models.CASCADE, default=10)
nome = models.CharField(max_length=200)
descricao = models.TextField()
quantidade = models.DecimalField(max_digits=10, decimal_places=3)
custo = models.DecimalField(max_digits=10, decimal_places=2)

def __str__(self):
    return self.nome

e

class Produto(models.Model):
nome = models.CharField(max_length=200)
descricao = models.TextField()
ingredientes = models.ManyToManyField(Ingrediente)
utilitarios = models.ManyToManyField(OutrosCustos)

def __str__(self):
    return self.nome

我使用此view返回包含Produto类的所有对象的列表:

def produtos_list(request):
produtos = Produto.objects.filter()
return render(request, 'egg_app/produtos_list.html', {'produtos':produtos})

在我的模板中,我这样写:

<table class="table">
<thead>
    <tr>
        <th scope="col">Nº Produto</th>
        <th scope="col">Nome</th>
        <th scope="col">Ingredientes</th>
        <th scope="col">Custo</th>
    </tr>
</thead>
<tbody>
    {% for p in produtos %}
        <tr>
            <th scope="row">{{ p.pk }}</th>
            <td>{{ p.nome }}</td>
            <td>{{ p.ingredientes }}</td>
            <td>custo teste</td>
        </tr>
    {% endfor %}
</tbody>
</table>

但是我在Ingredientes列中的结果是egg_app.Ingrediente.None,而不是该关系的成分名称(在IngredienteProduto之间)。在我的Django管理页面中,我将其关联了,所以我确定这种关系。

0 个答案:

没有答案
相关问题