سؤال

I'd like to remove 3 objects from my queryset. This working with the help of an extra list, but im pretty sure there should be a better way to do this with the QuerySet API. However I didnt figure out how yet:

What I'm doing:

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)

How can I do this using the Django API ?

هل كانت مفيدة؟

المحلول

try

remove_ranks = ['Field Marshall', 'Military Attache', 'Mercenary Recruiter']
Rank.objects.exclude(name__in=remove_ranks)

what does it do?

.exclude is the opposite of .filter

name__in is the equivalent of a IN-Statement in SQL

This should produce a sql query something along the line

Select * from rank where name not in ('Field Marshall', 'Military Attache', 'Mercenary Recruiter')
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top