假设我有以下两个模型:
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将自动创建一个向后关系,通过以下查询可以访问一个人的所有车辆:
^{pr2}$这将归还所有与该人有关的车辆,目前为止还不错。在
现在假设我想得到过滤了车辆的person对象,假设我只想要自行车类型的车辆。我怎么能那样做?在
为了将问题放在上下文中,我尝试构建以下URL:
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]
谢谢。在
顺便说一句,使用
type
作为字段名并不是很好,因为它是python保留的关键字。试着改成vehicle_type
。在编辑:
如果需要person对象,请执行以下操作:
^{pr2}$检查关于chaining filters的django文档。在
重新编辑:
要获得一个人拥有的自行车,您需要:
相关问题 更多 >
编程相关推荐