我有一个(简化的)Django模型,类似于以下内容:
models.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
,其中每个模板都已过滤。
views.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简化):
template.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 %}
如何将对象传递给模板,以便我可以采用与上述类似的方式处理它们?
答案 0 :(得分:0)
您的第一个代码段可以简化为这一次调用:
hotels = Hotel.objects.filter(roomtype__room=<whatever your criteria are>)
您无法在模板中执行此查询,但您可以将该hotels
查询集传递给模板以进行渲染。