在Djang中过滤单个对象的反向关系

2024-05-14 20:01:02 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有以下两个模型:

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]

谢谢。在


Tags: ofthename模型modelmodelstypeclass
1条回答
网友
1楼 · 发布于 2024-05-14 20:01:02
person.vehicles.filter(type='Bike')

顺便说一句,使用type作为字段名并不是很好,因为它是python保留的关键字。试着改成vehicle_type。在

编辑:

如果需要person对象,请执行以下操作:

^{pr2}$

检查关于chaining filters的django文档。在

重新编辑:

要获得一个人拥有的自行车,您需要:

person = Person.objects.get(pk=1)
all_bikes = person.vehicles.filter(type="Bike")

相关问题 更多 >

    热门问题