我有一个(简化的)Django 模型,类似于以下内容:
模型.py
# python
class Hotel(models.Model):
name = models.Charfield()
class RoomType(models.Model):
hotel=models.ForeignKey(Hotel, related_name="roomtypes")
price=models.IntegerField() # really a currency field
class Room(models.Model):
hotel = models.ForeignKey(Hotel)
roomType = models.ForeignKey(RoomType, related_name="rooms")
class Reservation(models.Model):
room = models.ForeignKey(Room)
date = models.DateField()
所以我的模板需要的层次结构是Hotel->RoomType->Room
每个都被过滤的地方。
视图.py
# only get available rooms that meet the user supplied criteria in q
q = Q() # complex query building omitted
rooms = Room.objects.filter(q)
# only get roomtypes that have rooms meeting criteria in q
roomTypesValues = rooms.values_list('roomType', flat=True)
roomTypes = RoomType.objects.filter(pk__in=list(roomTypesValues))
# only get hotels that have rooms meeting criteria in q
hotelsValues = roomTypes.values_list('hotel', flat=True)
hotels = Hotel.objects.filter(pk__in=list(hotelsValues))
c=RequestContext(request, {'hotels': hotels})
在某种程度上,这些查询中的每一个都有效。我还没有弄清楚如何在模板中使用它们。
我试图让这样的东西工作(HTML简化):
模板.html
{% for hotel in hotels %}
<h1>{{hotel.name}}</h1>
<ul>
{% for roomtype in hotel.roomtypes %}
<li>
{{roomtype.name]}, {{roomtype.price}}
{% for room in roomtype.rooms %}
<!-- not really needed for this -->
{% endfor %}
</li>
{% endfor %}
</ul>
{% endfor %}
如何将对象传递给模板,以便以与上述类似的方式处理它们?