[Answered ]-Django Models Select a car model based on Car Make

1👍

Use related_name for backwards compatibility.

class CarModel(models.Model):
    year = models.IntegerField(default=datetime.datetime.today().year)
    make = models.ForeignKey(Make, on_delete=models.CASCADE, related_name="models") # Note the related name here
    model = models.CharField('Model', max_length=150)
    trim = models.CharField('Trim', max_length=150, help_text='Trim level')

Then when you have a related name, you can easily access it by calling models on an instance

make = Make.objects.get(make="Dodge")
print(make.models) # Viper, Charger, Challenger, etc.

Note: make = Make.objects.get(make="Dodge") this will fire you an error if there are multiple records with the same query.

So you have to do something like this:

make = Make.objects.filter(make="Dodge") # return list of records`

Leave a comment