python - 在 Django 中过滤单个对象的反向关系

标签 python django api rest django-rest-framework

假设我有以下两个模型:

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/

相关文章:

java - 如何使用 Bukkit API 调用类方法?

python Boto3 S3 : List only current directory file ignoring subdirectory files

python - 有没有办法让 ConfigParser 'not' 返回列表

Python 求质因数

python - 如何反序列化 django rest 框架中的多个对象列表?

django - 查询效率

angularjs - 如何测试使用 MEAN 堆栈 API 的 Angular 前端

json - 如何在 flutter 中发送多部分请求中的对象列表?

javascript - 删除 Facebook 帖子的脚本

asp.net - Sql Server数据->MySql + Django迁移