So let’s say I have three models: User, CarBrand, CarModel, CarCharacteristics. The CarCharacteristics model describes how a user rates the characteristics of a car. So there can be many CarCharacteristics objects for a user, and a user can have many CarCharacteristics.
This is what my models look like:
class User(models.Model):
id = models.AutoField(primary_key=True)
class CarBrand(models.Model):
idcar_brand = models.AutoField(primary_key=True)
class CarModel(models.Model):
idcar_model = models.AutoField(primary_key=True)
car_brand = models.ForeignKey(CarBrand, null=True, on_delete=models.SET_NULL)
class CarCharacteristics(models.Model):
idcar_characteristics = models.AutoField(primary_key=True)
user = models.ForeignKey(User, on_delete=models.PROTECT)
car_model = models.ForeignKey(CarModel, on_delete=models.PROTECT)
What I would like to do is to get all CarBrand objects where a User has a CarCharacteristics. This is what am I doing right now:
car_chars = CarCharacteristics.objects.filter(user=user_id)
car_brands_ids = []
for car_char in car_chars:
brand_id = car_char.car_model.car_brand.idcar_brand
if brand_id not in car_brands_ids:
car_brands_ids.append(brand_id)
brands = CarBrand.objects.filter(idcar_brand__in=brand_ids)
Is there a simpler way of doing this? And how do I get all the CarModels where there exists a CarCharacteristics?
I think I figured it out. I think this works:
EDIT
Is what I have above also equivalent to this: