我在一个模型中有一个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
问题来源StackOverflow 地址:/questions/59386272/i-got-the-first-result-only-of-the-for-loop-in-django-views
可能您应该获得表的最后一个条目,除非您的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的比例。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。