Django跨越外键查询过滤的查询集

时间:2017-06-16 06:00:35

标签: django django-models

我有一个这样的模型集:

class Category(models.Model):
    name = models.CharField()

class CarModel(models.Model): 
    name = models.CharField()
    category = models.ForeignKey(Category, on_delete=models.CASCADE)

class Car(models.Model):
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    car_model = models.ForeignKey(CarModel, null=True, on_delete=models.CASCADE)

如何获取当前用户拥有的所有汽车类别的查询集?

谢谢! Ť

1 个答案:

答案 0 :(得分:0)

你可以,

Car.objects.filter(owner=request.user).select_related('car_model__category').all()