假设我有以下两个模型:
class Person(models.Model):
"""
A person model with the name of the person.
"""
name = models.CharField()
class Vehicle(models.Model):
"""
A vehicle model with the owner of the vehicle, and the type of the vehicle.
A vehicle type could be a car, a truck or a bike.
"""
owner = Models.ForeignKey(Person, related_name='vehicles')
type = models.CharField()
使用这两个模型,Django 将自动创建一个后向关系,其中可以通过以下查询访问一个人的所有车辆:
person = Person.objects.get(pk=1)
person.vehicles.all()
这将返回与该人相关的所有车辆,到目前为止一切顺利。
现在假设我想要过滤车辆的人对象,假设我只想要自行车类型的车辆。我怎么能那样做?
为了将问题放在上下文中,我正在尝试构建以下网址:
api.example.com/v1/person/1/vehicles/ [returns all vehicles]
api.example.com/v1/person/1/vehicles/?type=bike [returns only vehicles of type bike]
谢谢。
最佳答案
person.vehicles.filter(type='Bike')
顺便说一句,使用 type
作为字段名并不是很好,因为它是 python 保留关键字。尝试将其设为 vehicle_type
。
编辑:
如果你想要人物对象,做:
Person.objects.filter(vehicles__type="Bike")
查看有关 chaining filters 的 django 文档.
重新编辑:
要获得一个人拥有的自行车,您需要:
person = Person.objects.get(pk=1)
all_bikes = person.vehicles.filter(type="Bike")
关于python - 在 Django 中过滤单个对象的反向关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35003066/