所以我稍微修改了你的代码,设置了数据库,创建了 2 个Vehicle
对象,每个对象有 2 个相关Wheels
对象,所以Wheels
总共有 4 个对象。
我添加了一个函数,用于查询Wheel
某个对象的第一个相关Vehicle
对象。
# models.py
class Vehicle(models.Model):
vehicle_id = models.AutoField(primary_key=True)
vehicle_name = models.CharField(max_length=100)
color = models.CharField(max_length=100)
# this function returns a slice of the resulting queryset which contains
# the first related Wheels object for each Vehicle object
def get_first_wheels(self):
return Wheels.objects.filter(color=self).order_by('wheels_id')[:1]
class Wheels(models.Model):
wheels_id = models.AutoField(primary_key=True)
color = models.ForeignKey(Vehicle, null=True, on_delete=models.SET_NULL)
wheel_name = models.CharField(max_length=100)
我使用Django 序列化程序来序列化数据。为了获得第一个相关Wheels
对象,我使用了一个SerializerMethodField()
这样调用get_first_wheels()
函数的对象models.py
:
# serializers.py
class WheelsSerializer(serializers.ModelSerializer):
class Meta:
model = Wheels
fields = ('wheels_id', 'color', 'wheel_name')
class VehicleSerializer(serializers.ModelSerializer):
first_wheel = serializers.SerializerMethodField(read_only=True)
def get_first_wheel(self, model):
qs = model.get_first_wheels()
return WheelsSerializer(qs, many=True).data
class Meta:
model = Vehicle
fields = ('vehicle_id', 'vehicle_name', 'color', 'first_wheel')
我稍微改变了你的看法,改用了 a ModelViewSet
。
# views.py
class VehicleViewSet(viewsets.ModelViewSet):
serializer_class = VehicleSerializer
queryset = Vehicle.objects.all()
我去使用 aDefaultRouter()
来注册端点,如下所示:
# urls.py
from rest_framework import routers
# import ViewSet here
router = routers.DefaultRouter()
router.register(r'vehicles`, views.VehicleViewSet, base_name='vehicle')
然后我运行了以下命令:
manage.py makemigrations
manage.py migrate
manage.py runserver
我创建了 2 个Vehicle
对象,每个对象有 2 个相关Wheels
对象。
当我进入http://127.0.0.1:8000/vehicles/
浏览器时,它会返回所有Vehicle
对象及其第一个相关Wheels
对象,如下所示:
[
{
"vehicle_id": 1,
"vehicle_name": "BMW",
"color": "Blue",
"first_wheel": [
{
"wheels_id": 1,
"color": 1,
"wheel_name": "BMW1"
}
]
},
{
"vehicle_id": 2,
"vehicle_name": "Ferrari",
"color": "Red",
"first_wheel": [
{
"wheels_id": 3,
"color": 2,
"wheel_name": "Ferrari1"
}
]
}
]