Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Django 对象过滤器-需要建议_Django_Django Models_Django Views - Fatal编程技术网

Django 对象过滤器-需要建议

Django 对象过滤器-需要建议,django,django-models,django-views,Django,Django Models,Django Views,假设我有三个模型: class ONE (models.Model): [some awesome stuff] class TWO (models.Model): one = models.ForeignKey(ONE) user = models.ForeignKey(User) [other stuff] class THREE (models.Model): one = models.ForeignKey(ONE) [stuff and

假设我有三个模型:

class ONE (models.Model):
    [some awesome stuff]

class TWO (models.Model):
    one = models.ForeignKey(ONE)
    user = models.ForeignKey(User)
    [other stuff]

class THREE (models.Model):
    one = models.ForeignKey(ONE)
    [stuff and whatnot]
视图当前看起来如下所示:

def my_view(request, username, template_name='view.html'):
    current_user = get_object_or_404(User, username=username)
    two = TWO.objects.filter(user_id=current_user)
    three = THREE.objects.filter(one_id=two)

    data = {
        'user': current_user, 
        'two': two,
        'three': three
    }

    return render(request, template_name, data)
数据库条目是(这是简化的;每个表中有更多的数据):

在上面的视图中,我无法显示表3中的所有条目,其中表2中的user_id=1

错误消息=
用作表达式的子查询返回多行

我尝试使用
three=three.objects.filter(one\u id\u\u in=two)
,但在html页面上没有显示任何内容。也没有错误消息

HTML:

{%for two-in-two%}
{{two.one}}

{%endfor%} {三分之三的百分比为%1}
  • {{3}}
{%endfor%}

有适合我需要的过滤器选项吗?

请尝试更正过滤器中的
\u。参数必须是
列表
实例,而不是
查询集

two = TWO.objects.filter(user_id=current_user)
two_ids = two.values_list('id', flat=True).distinct('id')
three = THREE.objects.filter(one_id__in=two_ids)
distinct
此处不是必需的,但强烈建议使用

更多信息请访问

变量的
响应是什么样子的?这是一个错误<代码>响应
=
两个
。修好了。
{% for two in two %}
    <p>{{ two.one }}</p> <!-- that works! -->
{% endfor %}
{% for three in three %}
<ul>
    <li>{{ three }}</li>
</ul>
{% endfor %}
two = TWO.objects.filter(user_id=current_user)
two_ids = two.values_list('id', flat=True).distinct('id')
three = THREE.objects.filter(one_id__in=two_ids)