所以我想说我有三个模型: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)
我想要的是获取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
?
答案 0 :(得分:1)
试试这个:
CarBrand.objects.exclude(carmodel__carcharacteristics__user=None).distinct()
答案 1 :(得分:1)
我想我明白了。我认为这有效:
user_id = request.user.pk
brands = CarBrand.objects.exclude(~Q(carmodel__carcharacteristics__user=user_id))
修改强>
我上面的内容也与此相同:
user_id = request.user.pk
car_models = CarModel.objects.filter(carcharacteristics__user=user_id)
brands = CarBrand.objects.filter(carmodel__in=car_models).distinct()
答案 2 :(得分:0)
CarBrand.objects.filter(carmodel__carcharacteristics__user=request.user).distinct()