98đź‘Ť
You can use exclude()
in place of filter()
:
Entry.objects.exclude(name__contains="SomeString")
(“give me all entries EXCEPT those with names
containing “SomeString”)
And when dealing with Q object you can use “~” symbol before Q object to represent negation. For example the following statement means “give me all Entries with names
containing “Elephant”, but NOT containing “SomeString”:
Entry.objects.filter(Q(name__contains="Elephant") & ~Q(name__contains="SomeString"))
In some cases you may want to use both methods:
Entry.objects.exclude(Q(name__contains="Elephant") & ~Q(name__contains="SomeString"))
(“give me all entries, EXCEPT those with names
containing “Elephant”, but NOT containing “SomeString”)
- [Django]-How to write setup.py to include a Git repository as a dependency
- [Django]-Can't compare naive and aware datetime.now() <= challenge.datetime_end
- [Django]-Iterating through two lists in Django templates
3đź‘Ť
Either use exclude
as Hank suggests or, for the particular contains
case, use Q(name__regex=r’!(SomeString)’) if you really really need to use the filter
. Be warned though that regex
is not database-agnostic, check what syntax your db supports first.
- [Django]-Uncaught TypeError: Cannot read property 'ownerDocument' of undefined
- [Django]-How do I filter ForeignKey choices in a Django ModelForm?
- [Django]-Django urlsafe base64 decoding with decryption