0
在我的序列化程序中,我將字段設置爲非必需。Django rest框架返回非必需字段
當我串行化模型實例時,該字段不在輸出中。
如何在輸出中包含此字段?
class Client(models.Model):
user = models.OneToOneField(User)
profile_photo = models.ImageField(upload_to='pictures/profile_photos')
phone = models.CharField(max_length=100, default="")
class ClientSerializer(serializers.ModelSerializer):
username = serializers.CharField(source='user.username')
profile_photo = serializers.ImageField(source='details_sample.profile_photo', required=False)
class Meta:
model = Client
fields = ('id', 'username', 'profile_photo', 'phone')
@api_view(['GET'])
def get_user_info(request):
client = Client.objects.get(user=request.user)
serialized = ClientSerializer(client)
return Response(serialized.data) # no profile_photo
你能幫幫我嗎?
我不知道Django的,但我認爲圖像的來源是錯誤的。您說'details_sample.profile_photo',但客戶端實例中沒有details_sample字段。試試'source ='profile_photo''。無論如何,這只是一個猜測。 – yacc
將您的序列化程序更改爲source ='profile_photo'並且它可以正常工作。 – user6399774