[Django]-Q object for CheckConstraint

4👍

You can write this as:

  Q(available_on_the_store=False) |
  Q(price_A__isnull=False) |
  Q(price_B__isnull=False) |
  Q(price_C__isnull=False) |
  Q(price_D__isnull=False)

or we can write it shorter with:

Q(
    ('available_on_the_store', False),
    ('price_A__isnull', False),
    ('price_B__isnull', False),
    ('price_C__isnull', False),
    ('price_D__isnull', False),
    _connector=Q.OR
)

You thus can make a model that looks like:

class MyModel(models.Model):
    # …

    class Meta:
        constraints = [
            models.CheckConstraint(
                Q(
                    ('available_on_the_store', False),
                    ('price_A__isnull', False),
                    ('price_B__isnull', False),
                    ('price_C__isnull', False),
                    ('price_D__isnull', False),
                    _connector=Q.OR
                ),
                name='one_price_not_null_if_avaiable'
            )
        ]

Leave a comment