我有一個ImageField。當我使用.update命令更新它時,它不能正確保存。它驗證,返回一個成功的保存,並說它是好的。然而,圖像從來沒有保存過(我沒有像我做過其他圖片那樣在我的/媒體中看到它),並且在稍後投放時,它位於沒有圖片的/ media/Raw%@ 0Data。當使用文章存儲圖像時,它可以正常存儲。任何想法有什麼不對,它是否與嵌套的序列化程序有關?使用.update與嵌套序列化器發佈圖像
class MemberProfileSerializer(serializers.ModelSerializer):
class Meta:
model = MemberProfile
fields = (
'profile_image',
'phone_number',
'is_passenger',
'is_owner',
'is_captain',
'date_profile_created',
'date_profile_modified',
)
class AuthUserModelSerializer(serializers.ModelSerializer):
member_profile = MemberProfileSerializer(source='profile')
class Meta:
model = get_user_model()
fields = ('id',
'username',
'password',
'email',
'first_name',
'last_name',
'is_staff',
'is_active',
'date_joined',
'member_profile',
)
def update(self, instance, validated_data):
profile_data = validated_data.pop('profile')
for attr, value in validated_data.items():
if attr == 'password':
instance.set_password(value)
else:
setattr(instance, attr, value)
instance.save()
if not hasattr(instance, 'profile'):
MemberProfile.objects.create(user=instance, **profile_data)
else:
#This is the code that is having issues
profile = MemberProfile.objects.filter(user=instance)
profile.update(**profile_data)
return instance
在上面,你會看到profile = MemberProfile.objects.filter(user = instance),然後是update命令。這不是根據模型正確保存圖像。
class MemberProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, unique=True, related_name='profile')
profile_image = models.ImageField(
upload_to=get_upload_path(instance="instance",
filename="filename",
path='images/profile/'),
blank=True)
什麼明確記載的答案,謝謝。 – Diesel