我有两个模型,我想调用与两个模型中都存在的外键关联的字段值。 例如: 假设我们有两个模型:
from django.db import models
from django.contrib.auth.models import User
class Bike(models.Model):
bike_model = models.CharField(max_length=200)
owner = models.ForeignKey(User,on_delete=models.CASCADE)
class Car(models.Model):
car_model = models.CharField(max_length=200)
owner = models.ForeignKey(User,on_delete=models.CASCADE)
与之相关的序列化器类为:
from rest_framework import serializers
from .models import Bike,Car
class BikeSerializer(serializers.ModelSerializer):
class Meta:
model = Bike
fields = ('bike_model','owner')
class CarSerializer(serializers.ModelSerializer):
class Meta:
model = Car
fields = ('car_model','owner')
现在,我想在BikeSerializer中添加一个字段,以获取与给定所有者关联的所有汽车。那就是我要进行以下更改:
class BikeSerializer(serializers.ModelSerializer):
cars_owned = ???
class Meta:
model = Bike
fields = ('bike_model','owner','cars_owned')
我不知道如何归还所有者拥有的汽车。因此,对于来自序列化器的数据,我需要自行车模型,所有者ID以及所有者拥有的所有汽车ID的列表。
答案 0 :(得分:0)
您应该看这个SerializerMethodField。 基本上,您需要在BikeSerializer中创建一个方法来返回拥有的汽车。
class BikeSerializer(serializers.ModelSerializer):
cars_owned = serializers.SerializerMethodField()
class Meta:
model = Bike
fields = ('bike_model','owner','cars_owned')
def get_cars_owned(self, object):
# This is your query to get all cars associated
return object.cars_owned.all()
答案 1 :(得分:0)
您可以将seializer添加为字段:
class BikeSerializer(serializers.ModelSerializer):
cars_owned = CarSerializer(source='owner.car_set', many=True, read_only=True)
class Meta:
model = Bike
fields = ('bike_model','owner','cars_owned')