Я пытаюсь расширить модель в приложении Django. Единственная проблема, которая у меня есть, заключается в том, что мне нужно также расширить ограничения модели, и это не работает должным образом.
Это исходное ограничение для объекта в models.py:
models.CheckConstraint(
check=(
models.Q(inventory_item__isnull=True, device_type__isnull=False)
| models.Q(inventory_item__isnull=False, device_type__isnull=True)
),
name = "At least one of InventoryItem or DeviceType specified.",
)
Я попытался расширить его так:
models.CheckConstraint(
check=(
models.Q(inventory_item__isnull=True,
device_type__isnull=False,
module_type__isnull=False)
| models.Q(inventory_item__isnull=False,
device_type__isnull=True,
module_type__isnull=False)
| models.Q(inventory_item__isnull=False,
device_type__isnull=False,
module_type__isnull=True)
),
name = "At least one of InventoryItem, ModuleType or DeviceType specified.",
),
Вот как это выглядит в миграции:
migrations.AddConstraint(
model_name='hardwarelcm',
constraint=models.CheckConstraint(check=models.Q(models.Q(('device_type__isnull', False), ('inventory_item__isnull', True), ('module_type__isnull', False)), models.Q(('device_type__isnull', True), ('inventory_item__isnull', False), ('module_type__isnull', False)), models.Q(('device_type__isnull', False), ('inventory_item__isnull', False), ('module_type__isnull', True)), _connector='OR'), name='At least one of InventoryItem or ModelType or DeviceType specified.'),
)
Моя проблема в том, что я пробовал все комбинации, и каждый раз это терпит неудачу, но из сообщения об ошибке я вижу, что установлено только одно значение, а другое равно Null.
DETAIL: Failling row contains (3, null, 1, null)
Есть ли какие-то ограничения с объектами Q, которые я не понимаю? Я пытался прочитать документацию Django, но не смог понять, в чем проблема.
Ваше условие делает обратное: оно требует, чтобы элементы два не были None
. Вы должны сделать проверку с помощью:
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.'
)
Это означает, что вы можете указать точно один. Если вы хотите указать по меньшей мере, вы можете работать с:
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.'
)