Django:查询&将查询集中的对象渲染到列表中

时间:2011-05-01 05:17:32

标签: django django-views django-queryset

我正在对一个对象进行查询,该对象是另一个对象上的ForeignKey字段,并尝试将第二个查询呈现为列表。是否有正确的方法来访问第二个查询,因为我要在列表中呈现对象 - 但它无法访问。

mymeals = Meal.objects.filter(user=request.user.id)
reservations = []
for meal in mymeals:
    reservation = Reservation.objects.filter(meal=meal)
    reservations.append(reservation)

这样可行,但forloop呈现 - [ < Reservation: Reservation object > ]

 {% for reservation in reservations %}
  <p>{{reservation}} {{reservation.user.first_name}}</p>
 {% endfor %}

如何才能正确呈现预约对象,以便显示用户名?

1 个答案:

答案 0 :(得分:0)

mymeals = Meal.objects.filter(user=request.user.id)
reservations = Reservation.objects.filter(meal__in=mymeals)