对象过滤器 - 需要建议

时间:2014-02-16 08:36:31

标签: 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 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)

数据库条目是(这是简化的;每个表中有更多数据):

Table ONE
----------
id=1
id=2
id=3

Table TWO
----------
one_id=1; user_id=1
one_id=2; user_id=1
one_id=3; user_id=1

Table THREE
----------
one_id=1
one_id=2
one_id=3

根据上面的观点,我无法显示表格TH中表格TWO中user_id = 1的所有条目。

错误讯息= more than one row returned by a subquery used as an expression

我尝试使用three = THREE.objects.filter(one_id__in=two)但是在html页面上没有显示任何内容。也没有错误消息。

HTML:

{% for two in two %}
    <p>{{ two.one }}</p> <!-- that works! -->
{% endfor %}
{% for three in three %}
<ul>
    <li>{{ three }}</li>
</ul>
{% endfor %}

我的需求是否有过滤选项?

1 个答案:

答案 0 :(得分:0)

尝试更正__in过滤器。参数必须是list实例,而不是QuerySet

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这里不是必需的,但强烈建议。

https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.values_list查看更多信息 https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.distinct