我只得到了Django视图中for循环的第一个结果

2024-04-20 10:04:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个模型中有一个PositiveIntegerField,我需要在这个模型中循环检查这个字段的所有值,并得到它的结果,以便在我的视图中使用它。。你知道吗

问题是当我这样做时,我只得到数据库中第一行的值!你知道吗

型号.py

class RoomType(models.Model):
    hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE)
    room_type = models.ForeignKey(RoomTypesNames, on_delete=models.CASCADE)
    room_capacity = models.PositiveIntegerField() ## Thats the field i wanna check its value

视图.py

def SearchHotels(request):
    x = None
    z = None
    t = None

    if request.method == 'GET':
        destination = request.GET.get('cityHotels')
        numAdultStr = request.GET.get('numAdult')
        numChild = request.GET.get('numChild')
        numAdult = int(numAdultStr)

        if destination:
            q_city2 = Q(hotel__city__name__icontains = destination)
            rooms2  = RoomType.objects.filter(q_city2)
      ################################
      ### next is my question:
            if rooms2:
                for r in rooms2:
                    if r.room_capacity < numAdult and numAdult % r.room_capacity == 0:
                        x = numAdult / r.room_capacity

### i want to loop through this query and check the values of 'room_capacity' in all models, but i only get the result of only the first row in my database

Tags: thein模型nonegetifmodelsrequest
1条回答
网友
1楼 · 发布于 2024-04-20 10:04:42

除非order_by被反转,否则您可能应该获得表的最后一个条目。正如@furas在注释中提到的,当处理循环中的多个条目时,最好将计算值添加到列表中。你知道吗

但是另一种解决方案是使用^{}^{}来使用DB来为您计算值:

from django.db.models import FloatField, IntegerField, ExpressionWrapper, F, Case, When, Value

room2 = RoomType.objects.filter(q_city2).annotate(
    x_modulo=ExpressionWrapper(
            numAdult % F('room_capacity'),
            output_field=IntegerField()
         )
    ).annotate(
        x=Case(
            When(
                room_capacity__lt=numAdult,
                x_modulo=0,
                then=numAdult/F('room_capacity')
            ),
            default_value=Value('0'),
            output_field=FloatField()
        )
    )
all_x = []
for r in room2:
    all_x.append(r.x)
print(all_x)
# or
print(room2.values('x'))

# filter usage
room2.filter(x__gt=0)

解释:在这里,我是对x_modulo的注释,它是numAdult和room_capacity的模值。然后我注释x的值,它检查房间容量是否小于成人的数量,x_modulo的值是否为0。然后我只是注释numAdults和room_capacity的分数。你知道吗

相关问题 更多 >