开发者

Django query negation

开发者 https://www.devze.com 2022-12-18 20:19 出处:网络
I know how to build filters and Q objects in django, but I don\'t know how to negate the operators that the API provides, for example for the contains operator I would like something like notcontains.

I know how to build filters and Q objects in django, but I don't know how to negate the operators that the API provides, for example for the contains operator I would like something like notcontains.

e.g.

q=Q(name__notcontains="SomeString")

This would get me all objects whose name do not contain "SomeString".

开发者_高级运维

Is there some syntax that I'm missing?

Thankyou.


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")


Here's the QuerySet API reference. exclude seems to do what you want.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号