我如何在Django中执行此查询?

时间:2013-01-24 05:05:33

标签: django django-models django-queryset

所以我想说我有三个模型:UserCarBrandCarModelCarCharacteristicsCarCharacteristics模型描述了用户如何评价汽车的特征。因此,用户可以有许多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)

我想要的是获取CarBrandUser的所有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

3 个答案:

答案 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()