N
N
Neyury2016-11-30 12:46:11
Django
Neyury, 2016-11-30 12:46:11

Selection constraint in ManyToManyField in Django?

There are three models (tables): Product, Brand, BrandColors
Product - contains information about the product and brand association (ForeignKey)
Brand - description of the brand
BrandColors - contains the colors of the brand that it uses in its products (for one brand, several records describing its colors) (ForeignKey)
It is necessary that when editing a product in the admin panel, you can select several colors from the brand palette. To do this, I decided to add a ManyToManyField to the product to link with BrandColors, but all colors, of all brands, are shown in the admin panel. How to limit the list only to the colors of the brand that is registered in the product?
models.py

#Сокращенный вариант, неважные поля и параметры убраны
class Brand(models.Model):
    name = models.CharField()
    description = models.TextField()

class BrandColor(models.Model):
    brand = models.ForeignKey(Brand)
    name = models.CharField()
    color = models.CharField()

class Product(models.Model):
    brand = models.ForeignKey(Brand)
    colors = models.ManyToManyField(BrandColor)
    name = models.CharField()

I tried to limit using limit_choices_to , but it only worked out when I explicitly specified a specific brand id (and it can be different for products)
# модель Product
colors = models.ManyToManyField(BrandColor, limit_choices_to={'brand':  1})

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
osipov_am, 2017-10-26
@osipov_am

https://stackoverflow.com/a/14951304/3375252

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question