【问题标题】:How do I access the elements from this queryset in a template?如何在模板中访问此查询集中的元素?
【发布时间】:2013-03-29 11:12:27
【问题描述】:

这是查询集:

researches = Graph.objects.filter(subject=subject_object).exclude(type='infografik').values_list('name', flat=True).distinct()

当我这样做时:

{% for research in researches %}

在我的模板中,中间的代码执行了正确的次数,但例如 {{ research.name }} 不起作用。

如何访问对象的属性?

谢谢。

编辑:

图形模型

name = models.CharField(max_length=100)
research = models.ForeignKey('Research')
explanation = models.TextField(max_length=1000)
path_to_file = models.CharField(max_length=100)
type = models.CharField(max_length=30, choices=type, null=True, blank=True)
subject = models.ManyToManyField(Subject)
thumbnail = models.ImageField(upload_to='thumbnails/', null=True, blank=True)
slug = models.SlugField(max_length=120, unique=True)

【问题讨论】:

标签: django templates distinct django-queryset


【解决方案1】:

来自doc

每个元组都包含传入 values_list() 的各个字段的值

所以打印研究名称只需:

{% for research in researches %}
{{ research  }}
{% endfor %}

【讨论】:

    【解决方案2】:

    因为您要求的是一个平面的值列表,所以没有要访问的属性。如果您想访问所有属性,请使用此查询researches = Graph.objects.filter(subject=subject_object).exclude(type='infografik').distinct(),它将返回一个可以迭代的查询集,或者使用此researches = Graph.objects.filter(subject=subject_object).exclude(type='infografik').values().distinct(),它将返回一个字典列表。在 django 的模板语言中,您可以像这样访问两者的属性:

    {% for research in researches %}
        {{ research.name }}
        {{ research.author }}
        ...
    {% endfor %}
    

    我知道获得不同对象的唯一方法是使用原始 sql:

    researches = Graph.objects.raw('SELECT * FROM appname_graph WHERE subject_id = %s AND type <> %s GROUP BY name', [subject_object.id, 'infografik'])
    

    【讨论】:

    • 我需要的是得到一个列表,就像我删除重复值一样(不显示两个同名的 Graph 对象)。这是我通过此查询得到的,但我需要能够访问所有属性。你知道我该怎么做吗?
    • 好的,但这列出了我所有的对象,我已经尝试过了。问题是对象在各个方面都是不同的,除了“名称”属性,我需要让它们按名称不同。我用不了distinct('name')的问题,因为我不用PostgreSql。
    • @Tamara 你能发布你的 Graph 模型吗?
    猜你喜欢
    • 2020-12-22
    • 2020-01-16
    • 2012-12-28
    • 1970-01-01
    • 2021-02-07
    • 1970-01-01
    • 2016-03-07
    • 2023-03-27
    • 1970-01-01
    相关资源
    最近更新 更多