I am building a simple website for a car marketplace. I have written the brand, series and car models. (I purposefully want to treat each of them as seperate models.) Whenever I create a car in the admin panel I want to be able to pick a car brand – let’s say Mercedes – and when I choose the brand I want the next option to be only the series of Mercedes not the series of other cars.
Here is a representation of my code so far:
class Brand(models.Model):
brand = models.CharField(max_length=100)
class Series(models.Model):
brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
series = models.CharField(max_length=100)
class Car(models.Model):
brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
series = models.ForeignKey(Series, on_delete=models.CASCADE)
>Solution :
Use a ChainedForeignKey [readthedocs.io] instead from the django-smart-selects package [readthedocs.io]:
from smart_selects.db_fields import ChainedForeignKey
class Car(models.Model):
brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
series = ChainedForeignKey(
Series,
chained_field='brand',
chained_model_field='brand',
show_all=False,
on_delete=models.CASCADE,
)