Django,通过多个entry_set.all()关系过滤查询集

时间:2016-07-05 14:53:05

标签: python django django-models django-queryset

class Server(models.Model):
    client = models.ForeignKey(Client, on_delete=models.CASCADE)
    ...

class Schedule(models.Model):
    client = models.ForeignKey(Client, on_delete=models.CASCADE)
    ...

class LineItem(models.Model):
    schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE)
    server = models.ForeignKey(Server, blank=True, null=True)
    ...

我的模板中有一些非常讨厌的逻辑,用于显示与服务器详细信息页面中给定Server对象相关的任何LineItem

{% for schedule in server.client.schedule_set.all %}
    {% for lineitem in schedule.lineitem_set.all %}
        {% if lineitem.server == server %}
            {{ lineitem.id }}
            {{ lineitem.description }}
        {% endif %}
    {% endfor %}
{% endfor %}

更新:澄清

我可以通过以下方式从内部获取相关信息:

def serverDetailView(request, pk):
    # Fetches all the line items related to the current server
    server = get_object_or_404(Server, pk=pk)
    line_items = []
    for schedule in server.client.schedule_set.all():
        items = schedule.lineitem_set.all()
        for item in items:
            if item.server == server:
                line_items.append(item)
    context = {'server': server, 'line_items': line_items}
    return render(request, 'reports/server_detail.html', context)

然后在模板中:

{% for item in line_items %}
    {{ item }}
{% endfor %}

问题是,我可以使用单个查询过滤掉这些相关的LineItem吗?

1 个答案:

答案 0 :(得分:0)

而不是遵循反向关系model_set经理。您可以使用Django ORM中的双下划线符号来跟踪ForeignKey关系

line_items = LineItem.objects.filter(schedule__client=server.client)