Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I create categories and subcategories in django models?

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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,
    )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading