[Answered ]-Django Q objects in model constraints

1👍

Your condition does the opposite: it requires that two items are not None. You should make a check with:

from django.db.models import Q

models.CheckConstraint(
    check=Q(inventory_item=None, device_type=None, module_type__isnull=False) |
          Q(inventory_item=None, device_type__isnull=False, module_type=None) |
          Q(inventory_item__isnull=False, device_type=None, module_type=None),
    name='At least one of InventoryItem, ModuleType or DeviceType specified.'
)

This means that you can specify exactly one. If you want to specify at least one, you can work with:

from django.db.models import Q

models.CheckConstraint(
    check=Q(
        inventory_item__isnull=False,
        device_type__isnull=False,
        module_type__isnull=False,
        _connector=Q.OR
    ),
    name='At least one of InventoryItem, ModuleType or DeviceType specified.'
)

Leave a comment