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)
...
我的模板中有一些非常讨厌的逻辑,可以在服务器详细信息页面中显示与给定服务器对象相关的任何行项目
{% 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 %}
问题是,我可以通过单个查询筛选这些相关的订单项吗?
而不是遵循经理model_set
反向关系。你可以通过使用 Django ORM 中的双下划线表示法来跟踪ForeignKey
关系
line_items = LineItem.objects.filter(schedule__client=server.client)