我想从查询集中删除3个对象。这是在额外列表的帮助下工作,但我非常确定应该有更好的方法来使用QuerySet API。但是我还没弄明白:
我在做什么:
ranks = Rank.objects.all()
remove_ranks = ['Field Marshall', 'Military Attache', 'Mercenary Recruiter']
new_ranks =[]
for rank in ranks:
if not rank.name in remove_ranks:
new_ranks.append(rank)
如何使用Django API执行此操作?
答案 0 :(得分:3)
试
remove_ranks = ['Field Marshall', 'Military Attache', 'Mercenary Recruiter']
Rank.objects.exclude(name__in=remove_ranks)
它做了什么?
.exclude
与.filter
name__in
相当于SQL中的IN-Statement
这应该在行
上产生一些SQL查询Select * from rank where name not in ('Field Marshall', 'Military Attache', 'Mercenary Recruiter')