我有兩個模型之一,其中包含文本和其他圖像,並通過一個ForeignKey連接。該問題圍繞我的FortuneSerializer
中的pictures
屬性展開。爲了create
我不得不取消註釋並註釋掉另一個。而且,爲了正確顯示結果,我必須做同樣的事情(取消註釋/註釋掉)。我可以成功使用FortuneSerializer
中的修改後的create
方法,但顯示pictures
結果是一個問題。Django Rest框架 - 如何結合我的兩個序列化器?
當我使用PictureSerializer
的FortuneSerializer
結果內正確顯示,像這樣:
{
"id": 16,
"content": "win the lottery",
"pictures": [
{
"id": 2,
"image": "/media/2016/03/09/mypicture.png"
}
]
},
但是當他們正確顯示我無法使用create
捕捉的畫面。正因爲如此我註釋掉FortuneSerializer
並取消serializer.ImageField()
這將成功創建財富的實例和捕捉的畫面PictureSerializer
,但結果不顯示圖片的URL像這樣:
{
"id": 16,
"content": "win the lottery",
"pictures": null
},
串行器:
class PictureSerializer(serializers.ModelSerializer):
class Meta:
model = Picture
fields = ('id', 'image')
class FortuneSerializer(serializers.ModelSerializer):
# If uncommented, will display picture url in results, but can't create
pictures = PictureSerializer(many=True)
# If uncommented, will create Fortune with attached Picture,
# but will display `null` in results
pictures = serializers.ImageField(max_length=None, allow_empty_file=False)
class Meta:
model = Fortune
fields = ('id', 'content', 'pictures')
def create(self, validated_data):
pictures = validated_data.pop('pictures')
fortune = Fortune.objects.create(user=self.context['request'].user, **validated_data)
if pictures:
p=Picture(fortune=fortune)
p.image.save(str(pictures), pictures)
return fortune
型號:
class Fortune(models.Model):
user = models.ForeignKey(User, related_name='fortunes')
content = models.CharField(max_length=50)
class Picture(models.Model):
fortune = models.ForeignKey(Fortune, related_name='pictures')
image = models.ImageField(upload_to='%Y/%m/%d')
瀏覽:
class FortuneList(generics.ListCreateAPIView):
queryset = Fortune.objects.all()
serializer_class = FortuneSerializer
def list(self, request, user_id):
queryset = Fortune.objects.filter(user__id=user_id)
serializer = FortuneSerializer(queryset, many=True)
return Response(serializer.data)
任何解決方案?
====更新1 =====
我更新了FortuneSerializer
和PictureSerializer
爲@YPCrumble建議:
class FortuneSerializer(serializers.ModelSerializer):
class Meta:
model = Fortune
fields = ('id', 'content', 'pictures')
def create(self, validated_data):
pictures = validated_data.pop('pictures')
fortune = Fortune.objects.create(user=self.context['request'].user, **validated_data)
if pictures:
[Picture(fortune=fortune, image=picture) for picture in pictures]
return fortune
class PictureSerializer(serializers.ModelSerializer):
class Meta:
list_serializer_class = FortuneSerializer
我可以創建一個新的fortune
使用DRF默認的HTML帖子表單。該表格包含標題的文本輸入和用於選擇現有圖片文件的多選菜單(使用先前的串行器創建,其具有多文件選擇輸入)。我可以選擇單個或多個文件並創建fortune
而不會出現問題,並且現在將列出與新的fortune
關聯的圖片文件。不過,我想用fortune
發佈新圖片。表單中沒有文件輸入可供我選擇要上傳的新照片。任何指針?