Answer the question
In order to leave comments, you need to log in
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()
# модель Product
colors = models.ManyToManyField(BrandColor, limit_choices_to={'brand': 1})
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question