我有这样的模特:
class Car(models.Model):
name = models.CharField(max_length=255)
class CarImage(models.Model):
car = models.ForeignKey(Car, related_name='photos')
photo = models.ImageField(upload_to='car/')
对于我有的序列化器:
class CarImageSerializer(serializer.ModelSerializer):
class Meta:
model = CarImage
class CarSerializer(serializer.ModelSerializer):
photos = CarImageSerializer()
class Meta:
model = Car
fields = ('id', 'name', 'photos',)
当CarSerializer
的网页界面加载时,我默认会在non_field_errors
字段上获得photos
。这种事情是DRF支持的吗?如果不是最好的方法是什么?
P.S我使用通用CreateAPIView
答案 0 :(得分:1)
使用docs,您应该采用其他方式:
class CarSerializer(serializer.ModelSerializer):
photos = serializers.RelatedField(many=True)
class Meta:
model = Car
fields = ('id', 'name', 'photos',)
答案 1 :(得分:1)
也许你可以试试这个:
<强> serializers.py 强>
class CarImageSerializer(serializers.ModelSerializer):
class Meta:
model = CarImage
class CarSerializer(serializers.HyperlinkedModelSerializer):
photos = serializers.HyperlinkedRelatedField(many=True,
view_name='carimage-list')
class Meta:
model = Car
fields = ('id', 'name', 'photos',)
<强> views.py 强>
class CarImageList(ListCreateAPIView):
queryset = CarImage.objects.all()
serializer_class = CarImageSerializer
class CarList(ListCreateAPIView):
queryset = Car.objects.all()
serializer_class = CarSerializer
<强> urls.py 强>
url(r'^carimage/$', CarImageList.as_view(), name='carimage-list'),
url(r'^car/$', CarList.as_view(), name='car-list'),
你应该注意所有需要的进口。不能保证,但你可以尝试一下。