我在模型中有一个PositiveIntegerField,在其中需要遍历该模型以检查该字段的所有值,并获取其结果以在我的视图中使用它。
问题是当我这样做时,我只获得数据库中第一行的值!
models.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
views.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
最佳答案
除非您将order_by
反向,否则可能应该获得表的最后一个条目。正如@furas在评论中提到的那样,当您在循环中处理多个条目时,最好将计算值添加到列表中。
但是另一种解决方案是将annotate
与conditional expression
一起使用以使用数据库为您计算值:
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
的分数。关于python - 我仅在Django View 中获得了for循环的第一个结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59386272/