0

嗨,我有以下代码工作正常:

if getattr(hotel_main, "X", 1):
        hotels1 = hotels.filter(Q(X=True))
        for hotel in hotels1:
            if models.CalendarDay.objects.filter(hotel=hotel, date=date).count() == 0:
                similar_venues.append(hotel)

我一次又一次地重复使用上面的代码来检查不同的条件,比如 Q(Y=True),Q(Y=True),Q(Z=True)

如果我可以根据条件过滤列表,我可以摆脱重复的代码......我想要这样的东西:similar_venues.filter(Q(X=True)) 请帮忙......

4

2 回答 2

0

You can write conditions in a list:

conditions = [ Q(Y=True),Q(Y=True),Q(Z=True) ]
if getattr(hotel_main, "X", 1):
    q_date = Q( calendarday__date = date )
    for q in conditions:
        for hotel in hotels.filter( q_date & q).distinct():
            similar_venues.append(hotel)
于 2012-09-18T14:49:45.980 回答
0

如果我理解正确你的问题:

filter_on_x = [obj for obj in similar_venues if obj.X]
filter_on_y = [obj for obj in similar_venues if obj.Y]

依此类推,适用于所有 X、Y、Z

于 2012-09-18T14:47:22.267 回答