python - 无法从 Django 中的 ManyToManyField 检索值

标签 python django

我已经阅读了 QuerySet API 的文档和一些答案,但我似乎无法弄清楚这一点。我想我不理解这背后的概念。

所以,这是我的 models.py:

class Categoria(models.Model):
    TODOS = 'Todos'
    VEICULO = 'Veiculo'
    EQUIPAMENTO = 'Equipamento'
    SERVICO = 'Servico'
    OUTRO = 'Outro'

    CATEOGRY_CHOICES = (
        (TODOS, 'Todos'),
        (VEICULO, 'Veiculo'),
        (EQUIPAMENTO, 'Equipamento'),
        (SERVICO, 'Servico'),
        (OUTRO, 'Outro')
    )

    tipo = models.CharField(max_length=15, choices=CATEOGRY_CHOICES, default=TODOS)

    def __str__(self):
        return self.tipo

class Anuncio(models.Model):
    titulo = models.CharField(max_length=50)
    anuncio = models.TextField(max_length=200)
    preco = models.DecimalField(max_digits=6, decimal_places=2)
    contato = models.CharField(max_length=30)
    publicacao = models.DateTimeField()

    categoria = models.ManyToManyField(Categoria)

    def __str__(self):
        return self.titulo

然后,我将这个字典发送到 View :

{ 'anuncios' : Anuncio.objects.all()

这就是我显示值的方式:

{% for item in anuncios %}

        <div class="col-sm-6 col-md-4">
            <div class="thumbnail">
                <h3>{{ item.titulo }}</h3>
                <p>{{ item.anuncio }}</p>
                <address>{{ item.contato }}</address>
                <h6><a href="#">{{ item.categoria.all.values }}</a></h6>
            </div>
        </div>

{% endfor %}

但是我无法从 ManyToManyField 中获取正确的值。如果我使用 item.categoria ,我得到lista.Categoria.None (lista 是应用程序的名称)。如果我使用 item.categoria.all ,我得到<QuerySet [<Categoria: Servico>]> 。 如果我使用 item.categoria.all.values ,我得到<QuerySet [{'id': 7, 'tipo': 'Servico'}]> 。在这种情况下,我真正想要的只是“Servico”这个词。

此外,如果我尝试过滤某些内容,我会得到 TemplateSyntaxError at /消息 Could not parse the remainder: .

最佳答案

这是一个对多关系。不是只有一种,而是很多;所以你不能只访问“Servicio”,因为你可能有多个项目。您需要迭代:

{% for cat in item.categoria.all %}{{ cat.tipo }}{% endfor %}

关于python - 无法从 Django 中的 ManyToManyField 检索值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42033927/

相关文章:

python - Django Python 应用程序应该存储在 Web 服务器文档根目录中吗?

Python - 分组顺序数组成员

Python:在 lambda 中使用 lambda 返回 lambda 对象

python - 如何加速 python selenium find_elements?

python - 找不到该进程类型,Heroku

python - 带有 Redis 的 Django websockets

python - 如何在 django Rest 中自动继承外键模型的字段?

python - 如何在 python 中使用 linux 命令和 python 函数 (sys.argv)

django - 模拟文件数据来测试表单的正确方法是什么?

python - Django:使用Redis做Cache超时的含义