我编写了检查一个属性的方法,如果有一位艺术家的 selling=False 则返回 False,否则返回 True。
def check_selling(track, excludes):
"""
Returns True if all track's artists are allowed for selling. False otherwise
"""
for artist in track.artists.all():
if not artist.selling:
excludes.append(track.pk)
return False
return True
我怎样才能最大限度地减少这种情况?
我试过:
def check_selling(track, excludes):
res = excludes.append(track.pk) if not [artist.selling for artist in track.artists.all()] else True
return res or False
但是 [False] 或 [True] 导致列表理解 [artist.selling for artist in track.artists.all()] 总是给出 True...
最佳答案
进行查询! 参见 Here
def check_selling(track, excludes):
"""
Returns True if all track's artists are allowed for selling. False otherwise
"""
if track.artists.filter(selling=False).exists(): #If "selling" is a boolean
excludes.append(track)
return False
return True
只有一个查询
关于python - Django 优化方法中的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17153775/