Django Queryset return all if field is empty when there is OneToMany relationship

I have an html page in which one can search for a car based on several criteria. How do I tell django orm to return all if a field is empty? I checked this question and implemented the same idea of the first answer but it doesn't work for the foreign fields especially the model field, which if left empty, I get this error. Here are my classes

class City(models.Model):
    name = models.CharField(max_length=10, null=True)
    created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True)
    updated_at = models.DateTimeField(auto_now=True, null=True, blank=True)

class PowerSource(models.Model):
    source = models.CharField(max_length=8)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

class Manufacturer(models.Model):
    manufacturer = models.CharField(max_length=45)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

class CarModel(models.Model):
    model = models.CharField(max_length=45)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    manufacturer = models.ForeignKey(Manufacturer, related_name='car_models', on_delete=models.CASCADE)

class Car(models.Model):
    color = models.CharField(max_length=10, null=True)
    year = models.IntegerField(null=True, validators=[MinValueValidator(datetime.today().year-120), MaxValueValidator(datetime.today().year+1)])
    num_passengers = models.IntegerField(validators=[MinValueValidator(1)], null=True)
    transmission = models.CharField(max_length=9, null=True)
    status = models.CharField(max_length=4, null=True)
    price = models.IntegerField(validators=[MinValueValidator(1)], null=True)
    bhp = models.IntegerField(null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    city = models.ForeignKey(City, related_name='cars', on_delete=models.CASCADE)
    power_source = models.ForeignKey(PowerSource, related_name='cars', on_delete=models.CASCADE)
    model = models.ForeignKey(CarModel, related_name='cars', on_delete=models.CASCADE)

For example, if I choose a manufacturer and leave other fields empy I should get all cars from that manufacturer regardless of color, year, etc. However, I get the aforementioned error. If I choose a manufacturer and a model I don't get the error but the search result is empty. Any ideas?

Back to Top