假设我有三个模型:User
, CarBrand
, CarModel
, CarCharacteristics
。该CarCharacteristics
模型描述了用户如何评价汽车的特性。所以一个用户可以有很多CarCharacteristics
对象,一个用户可以有很多CarCharacteristics
.
这是我的模型的样子:
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)
我想做的是获取a有 a 的所有CarBrand
对象。这就是我现在正在做的事情:User
CarCharacteristics
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)
有没有更简单的方法来做到这一点?以及如何获得所有CarModels
存在的地方CarCharacteristics
?