Three valued logic

Because of the way SQL handles NULL, there are some special operationsavailable for expressing:

  • IS NULL
  • IS NOT NULL
  • IN
  • NOT IN

While it would be possible to use the IS NULL and IN operators with thenegation operator (~), sometimes to get the correct semantics you will needto explicitly use IS NOT NULL and NOT IN.

The simplest way to use IS NULL and IN is to use the operatoroverloads:

  1. # Get all User objects whose last login is NULL.
  2. User.select().where(User.last_login >> None)
  3.  
  4. # Get users whose username is in the given list.
  5. usernames = ['charlie', 'huey', 'mickey']
  6. User.select().where(User.username << usernames)

If you don’t like operator overloads, you can call the Field methods instead:

  1. # Get all User objects whose last login is NULL.
  2. User.select().where(User.last_login.is_null(True))
  3.  
  4. # Get users whose username is in the given list.
  5. usernames = ['charlie', 'huey', 'mickey']
  6. User.select().where(User.username.in_(usernames))

To negate the above queries, you can use unary negation, but for the correctsemantics you may need to use the special IS NOT and NOT IN operators:

  1. # Get all User objects whose last login is *NOT* NULL.
  2. User.select().where(User.last_login.is_null(False))
  3.  
  4. # Using unary negation instead.
  5. User.select().where(~(User.last_login >> None))
  6.  
  7. # Get users whose username is *NOT* in the given list.
  8. usernames = ['charlie', 'huey', 'mickey']
  9. User.select().where(User.username.not_in(usernames))
  10.  
  11. # Using unary negation instead.
  12. usernames = ['charlie', 'huey', 'mickey']
  13. User.select().where(~(User.username << usernames))