简体   繁体   English

使用嵌套循环迭代 django 模板中的多个查询集

[英]Iterate over several querysets in django template with nested loop

I am making a hotell-page, and have made models for bookings and rooms.我正在制作一个酒店页面,并为预订和房间制作了模型。 I want to display the bookings related to a room in a table, and have the related bookings laying under the spesific room.我想在表格中显示与房间相关的预订,并将相关预订放在特定房间下。 房间和预订表

I show the code from the views.py file here:我在这里展示了 views.py 文件中的代码:

def vaskehjelp(response):
available_rooms = Room.objects.filter(available=True)
room_nums = []
context = {}
for room in available_rooms:
    related_bookings = Booking.objects.filter(room=room)
    if related_bookings:
        room_nums.append(room.room_no)
        context[room.room_no] = related_bookings

context["room_nums"] = room_nums
context["available_rooms"] = available_rooms
print(context)
return render(response, "../templates/se_vaskbare_rom.html", context)

and the code from my template file here:以及我的模板文件中的代码:

<table class="table table-striped table-dark">
            <tr class="thead-dark">
                <th scope="col">Room No.</th>
                <th scope="col">Capacity</th>
                <th scope="col">Room Type</th>
            </tr>
            {% for item in available_rooms %}
                <tr scope="row">
                    <td>{{ item.room_no }}</td>
                    <td>{{ item.capacity }}</td>
                    <td>{{ item.room_type }}</td>
                </tr>
                {% if item.room_no in room_nums %}
                    {% for booking in item.room_no %}
                        <h1></h1>
                        <tr scope="row">
                            <td>{{ booking.cin_date }}</td>
                            <td>ku</td>
                            <td>{{ booking.cout_date }}</td>
                        </tr>
                    {% endfor %}
                {% endif %}
            {% endfor %}
        </table>

The problem is that the booking-element in the template code doesent seem to work.问题是模板代码中的预订元素似乎不起作用。 I dont manage to access the lists of bookings related to the current selected room.我无法访问与当前所选房间相关的预订列表。 As you see i have an outer for loop to iterate over the rooms, and then the inner for loop iterate over the related bookings (only in case that room is in the "room_nums" list. The problem is (i think) that the for booking in item.room_no doesnt work, i dont get any info from the booking variable at least...如您所见,我有一个外部 for 循环来遍历房间,然后内部 for 循环遍历相关预订(仅当该房间在“room_nums”列表中的情况下。问题是(我认为) for在 item.room_no 中预订不起作用,我至少没有从预订变量中获得任何信息......

In the table i should have had the check in and check out dates in the left and right column, but i dont get this information from the booking variable...在表格中,我应该在左右列中填写入住和退房日期,但我没有从预订变量中获取此信息...

ps: the idea is that item.room_no is referrering to a list in the context dictionary. ps:这个想法是 item.room_no 指的是上下文字典中的列表。 I have tried other things, but this is the closest i have come.我尝试过其他的东西,但这是我最接近的。

Here are the models :以下是模型

class Room(models.Model):
room_choices = [('S', 'Single Occupancy'), ('D', 'Double Occupancy'), ('F', 'Firemannsrom')]
room_no = models.CharField(max_length=5)  # primary key
available = models.BooleanField(default=False)
capacity = models.IntegerField(default=None)
room_type = models.CharField(choices=room_choices, max_length=1, default=None)
price = models.IntegerField( blank=True, null=True)

def __str__(self):
    return "Romnr: " + str(self.room_no) + " -- type:" + str(self.room_type)

and

class Booking(models.Model):
#defaultRom = Room.objects.get(room_no='100')
#defaultRomID = defaultRom.id
room_choices = [('S', 'Single Occupancy'), ('D', 'Double Occupancy'), ('F', 'Firemannsrom')]
bookingid = models.AutoField(db_column='BookingID', primary_key=True)  # Field name made lowercase.
guest = models.ForeignKey('auth.User', on_delete=models.CASCADE)  # eller settings.AUTH_USER_MODEL
cin_date = models.DateField(db_column='CIN_Date', blank=True, null=True,
                                verbose_name='Check-In Date')  # Field name made lowercase.
cout_date = models.DateField(db_column='COUT_Date', blank=True, null=True,
                                 verbose_name='Check-Out Date')  # Field name made lowercase.
room_type = models.CharField(choices=room_choices, max_length=1, default=None)
room = models.ForeignKey('Room', on_delete=models.CASCADE, db_column='Room', default=None)

class Meta:
    managed = True
    db_table = 'Booking'

def __str__(self):
    return "Bruker: " + self.guest.__str__() + " -- id:" + str(self.bookingid) + " -- Inndato: " +  self.cin_date.__str__() + " -- Utdato: " + self.cout_date.__str__() + " -- " + self.room.__str__()

Here is the the result of print(context) :这是print(context)的结果:

{'100': <QuerySet [<Booking: Bruker: email -- id:27 -- Inndato: 2020-03-27 -- Utdato: 2020-03-29 -- Romnr: 100 -- type:S>]>, '103': <QuerySet [<Booking: Bruker: olaNordmann -- id:26 -- Inndato: 2020-03-07 -- Utdato: 2020-03-15 -- Romnr: 103 -- type:D>]>, 'room_nums': ['100', '103'], 'available_rooms': <QuerySet [<Room: Romnr: 100 -- type:S>, <Room: Romnr: 103 -- type:D>, <Room: Romnr: 106 -- type:F>, <Room: Romnr: 101 -- type:S>]>}

Thanks in advance!提前致谢!

You are referencing to CharField defined in Room class instead of Booking queryset您正在引用 Room 类中定义的 CharField 而不是 Booking 查询集

a quick solution might be to change the code in a following way:一个快速的解决方案可能是通过以下方式更改代码:

{% for booking in item.related_bookings %}
    <h1></h1>
    <tr scope="row">
        <td>{{ booking.cin_date }}</td>
        <td>ku</td>
        <td>{{ booking.cout_date }}</td>
    </tr>
{% endfor %}
def vaskehjelp(response):
    available_rooms = Room.objects.filter(available=True)
    context = {}
    for room in available_rooms:
        related_bookings = Booking.objects.filter(room=room)
        if related_bookings:
            room_nums.append(room.room_no)
            room.related_bookings = related_bookings

    context["room_nums"] = room_nums
    context["available_rooms"] = available_rooms
    print(context)
    return render(response, "../templates/se_vaskbare_rom.html", context)

But I believe that the easiest solution is the following one:但我相信最简单的解决方案是以下一个:

def vaskehjelp(response):
    context = {}
    available_rooms = Room.objects.filter(available=True).prefetch_related('Room')
    context["available_rooms"] = available_rooms
    return render(response, "../templates/se_vaskbare_rom.html", context)
{% for item in available_rooms %}
    <tr scope="row">
        <td>{{ item.room_no }}</td>
        <td>{{ item.capacity }}</td>
        <td>{{ item.room_type }}</td>
    </tr>
    {% for booking in item.Room %}
        <h1></h1>
        <tr scope="row">
            <td>{{ booking.cin_date }}</td>
            <td>ku</td>
            <td>{{ booking.cout_date }}</td>
        </tr>
    {% endfor %}
{% endfor %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM