2

假设我有三个模型: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对象。这就是我现在正在做的事情:UserCarCharacteristics

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

4

3 回答 3

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()
于 2013-01-24T05:19:43.107 回答
1

尝试这个:

CarBrand.objects.exclude(carmodel__carcharacteristics__user=None).distinct()
于 2013-01-24T05:09:15.943 回答
0
CarBrand.objects.filter(carmodel__carcharacteristics__user=request.user).distinct()
于 2013-01-24T09:13:58.807 回答