Y
Y
Yzurgzd2020-10-24 18:14:06
Django
Yzurgzd, 2020-10-24 18:14:06

How to implement Filter in models.ForeignKey Django?

models

class Product(models.Model):
    name = models.CharField('Наименование', max_length=100)
    poster = models.ImageField('Постер', upload_to='products/posters/')
    description = models.TextField('Описание')
    category = models.ForeignKey(
        Category, verbose_name='Категория', on_delete=models.SET_NULL, null=True)
    price = models.PositiveIntegerField(
        'Цена', default=0, help_text='Указывать сумму в рублях')
    hide = models.BooleanField('Скрыть', default=False)
    slug = models.SlugField(max_length=160, unique=True)

class TypeSpecification(models.Model):
    category = models.ForeignKey(
        Category, verbose_name='Категория', null=True, on_delete=models.SET_NULL)
    name = models.CharField('Наименование', max_length=255)

class ProductSpecification(models.Model):
    product = models.ForeignKey(
        Product, verbose_name='Товар', on_delete=models.CASCADE)
    type_specification = models.ForeignKey(
        TypeSpecification, verbose_name='Тип характеристик', on_delete=models.CASCADE, limit_choices_to={'category': self.product.category})
    value = models.CharField('Значение', max_length=255)


It is necessary in the 'ProductSpecification' model, in the ForeignKey 'type_specification' field, to display data (from the 'TypeSpecification' model), only if the Category in the 'TypeSpecification' matches the Category in the Product. What is the best way to implement this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2020-10-24
@Yzurgzd

There is no way in the model, only filtering in the form, and then if the product value is known in advance. If the product is selected in realtime, then there is already ajax and other joys, the most famous library to help django-select2

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question