1

我有一个(简化的)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 %}

如何将对象传递给模板,以便以与上述类似的方式处理它们?

4

1 回答 1

0

您的第一个片段可以简化为这个单一的调用:

hotels = Hotel.objects.filter(roomtype__room=<whatever your criteria are>)

您不能在模板中执行此查询,但您可以将该查询集传递hotels给模板以在那里呈现。

于 2013-03-15T11:48:23.753 回答