Возможно ли иметь два параметра в limit_choices_to в моделях django?
Я сокращу код настолько, насколько это возможно. Предположительно, у нас есть две модели
models.py > Таблица продуктов
CATEGORY = (
('Hard Disk Drive', 'Hard Disk Drive'),
('Solid State Drive', 'Solid State Drive'),
('Graphics Card', 'Graphics Card'),
('Laptop', 'Laptop'),
('RAM', 'RAM'),
('Charger', 'Charger'),
('UPS', 'UPS'),
('Mouse', 'Mouse'),
('Keyboard', 'Keyboard'),
('Motherboard', 'Motherboard'),
('Monitor', 'Monitor'),
('Power Supply', 'Power Supply'),
('Router', 'Router'),
('AVR', 'AVR'),
('Tablet', 'Tablet'),
('System Unit', 'System Unit'),
('Audio Devices', 'Audio Devices'),
('CPU', 'CPU'),
('Others', 'Others'),
)
class Product(models.Model):
model_name = models.CharField(max_length=100, null=True, blank=True)
asset_type = models.CharField(max_length=20, choices=CATEGORY, blank=True)
date = models.DateField(null=True, blank=True)
Другой стол > Стол заказов
class Order(models.Model):
product_order = models.ForeignKey(Product, on_delete=models.CASCADE, null=False)
employee = models.ForeignKey(User, models.CASCADE, null=False)
date = models.DateTimeField(auto_now_add=True)
remarks = models.TextField()
И мы все знаем, что добавление этого кода ограничит выбор иностранных ключей в форме заказа.
limit_choices_to={"asset_type": "Hard Disk Drive"}
limit_choices_to={"asset_type": "Solid State Drive"}
Моя цель - показать элементы из таблицы Products, чей asset_type либо "Hard Disk Drive", либо "Solid State Drive". Я прочитал документацию Django для "limit_choices_to" и не могу увидеть здесь никакого относящегося к какому-то решению. Заранее благодарю тех, кто знает способ сделать это возможным.
Вы можете работать с __in поиском [Django-doc] для указания списка допустимых значений:
class Order(models.Model):
product_order = models.ForeignKey(
Product,
on_delete=models.CASCADE,
limit_choices_to=dict(asset_type__in=['Hard Disk Drive', 'Solid State Drive'])
)
# …
Note: Specifying
null=False[Django-doc] is not necessary: fields are by default not NULLable.
Note: It is normally better to make use of the
settings.AUTH_USER_MODEL[Django-doc] to refer to the user model, than to use theUsermodel [Django-doc] directly. For more information you can see the referencing theUsermodel section of the documentation.