模型的通用结构是有教师和设备,每个设备与教师ID / PK具有ForeignKey关系。
我正在尝试以这样一种方式创建我的API:当进入教师的详细信息视图时,将显示所有关联的设备。我已经覆盖了 get_serializer_class() 来指定在适当的时间使用哪个序列化程序,但无法弄清楚如何根据详细信息视图正确更改查询集。错误在下面发布。
Got AttributeError when attempting to get a value for field `brand` on serializer `DeviceSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `Teacher` instance.
Original exception text was: 'Teacher' object has no attribute 'brand'.
class TeacherViewSet(viewsets.ModelViewSet):
queryset = Teacher.objects.order_by('campus','name')
serializer_class = TeacherSerializer
detail_serializer_class = DeviceSerializer
def get_serializer_class(self):
if self.action == 'retrieve':
if hasattr(self, 'detail_serializer_class'):
return self.detail_serializer_class
return super(TeacherViewSet, self).get_serializer_class()
def get_queryset(self, pk=None):
if pk is not None:
return Device.objects.filter(device__owner=self.kwargs.get('pk')
return Teacher.objects.all()
答案 0 :(得分:2)
通过在我的TeacherSerializer中添加一个嵌套的DeviceSerializer来解析设备对象列表,我能够获得所需的输出。
class TeacherSerializer(serializers.ModelSerializer):
devices = DeviceSerializer(many=True)
class Meta:
model = Teacher
fields = ('id', 'name', 'campus', 'email', 'devices')
答案 1 :(得分:0)
我假设您正在使用DRF。如果是这种情况,只需将TeacherSerializer
调整为以下内容:
def TeachSearializer(serializer.ModelSerializer):
devices = serializers.SerializerMethodField()
class Meta:
model = Teacher
fields = '__all__'
def get_devices(self, obj):
return Devices.objects.filter(teacher=obj)
就是这样,每次您在教师对象上使用序列化程序时,其设备将添加到字段devices