如何return第一个序列化对象而不是Django中的全部?

How to return the first serialized object rather than all in Django?

我有一个 API(使用 django-rest-framework)和两个模型(例如 Users 和 Cars)。

我正在尝试获取用户的最新(最高 ID)汽车,在查询用户时也返回了。

我试过在用户序列化程序中包含 cars = CarSerializer(many=True),returns 该用户的所有汽车。

我试过 cars = CarSerializer(many=False),returns 我想要的格式,但是没有车出现。

代码

车型

class Car(models.Model):
    name = models.TextField(default='')
    year = models.IntegerField(null=True)
    owner = models.ForeignKey('User', related_name='cars')

汽车序列化器

class CarSerializer(serializers.ModelSerializer):

    class Meta:
        model = Car
        fields = ('id', 'name', 'year', 'owner')

用户序列化程序

class UserSerializer(serializers.ModelSerializer):
    car = CarSerializer(many=True)

    class Meta:
        model = User
        fields = ('id', 'first_name', 'last_name', 'car')

车景

class CarViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = Car.objects.all()
    serializer_class = CarSerializer

用户浏览

class UserViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

我在找什么

给定属于 ID 为 1 的用户的两辆车:

id: 1
owner: 1
name: "kinda okay car"
year: 2012

id: 2
owner: 1
name: "the fastest one"
year: 2020

JSON GET 的结果 /users/1

{
  "id": 1,
  "first_name": "Bob",
  "last_name": "McFastCar",
  "car": {
    "name": "the fastest one",
    "year": 2020
  }
}

我目前得到的

JSON GET 的结果 /users/1

{
  "id": 1,
  "first_name": "Bob",
  "last_name": "McFastCar",
  "cars": [
    {
      "id": 2,
      "owner": 1
      "name": "the fastest one",
      "year": 2020
    },
    {
      "id": 1,
      "owner": 1
      "name": "kinda okay car",
      "year": 2012
    }
  ],
}

谢谢,我希望你能帮助我找到解决方案。

CarSerializer 必须与查询集或对象链接,否则它将 return 所有对象

# get the car object with the highest using order_by
car =  Car.objects.all().order_by('-id')[0]
# build a car serializer from the car object
car_serializer = CarSerializer(car, many=False)

你可以像下面这样写 UserSerializers

class UserSerializer(serializers.ModelSerializer):
    cars = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = ('id', 'first_name', 'last_name', 'cars')

    def get_cars(self, instance):
        cars = instance.cars.all().order_by('-year')
        return CarSerializer([cars[0], ], many=True).data

调用 GET /users/1 将 return 结果如下

{
    "id": 2,
    "first_name": "Bob",
    "last_name": "McFastCar",
    "cars": [
        {
            "id": 2,
            "name": "the fastest one",
            "year": 2020,
            "owner": 2,
            "first_name": "Bob"
        }
    ]
}

下面的行给了我一个未知的错误所以我用 many=True

写了它
return CarSerializer(cars, many=False).data

您实际上可以在 User 模型中创建一个 @property,仅 returns 最后一辆车:

class User:
    ...

    @property
    def last_car(self):
        return self.cars.last()

然后在 UserSerializer 中你可以序列化这个 属性:

class UserSerializer:
    last_car = CarSerializer(read_only=True)

    class Meta:
        model = User
        fields = (..., 'last_car')

这样就可以了。


P.S. :如果您仍希望将最新的汽车条目序列化为 "car": { ... } 而不是 "last_car": { ... } ,您可以使用the source attributeCarSerializer 本身上:

class UserSerializer:
    car = CarSerializer(source='last_car', read_only=True)
    ...