2015-06-22 45 views
0

我有一個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) 

回答

1

如在該文檔所指出的,.update()不調用模型.save()或擊發post_save/pre_save信號對每個匹配的模型。它幾乎直接轉換爲SQL UPDATE聲明。 https://docs.djangoproject.com/en/1.8/ref/models/querysets/#update

最後,實現更新()在SQL級別做一個更新,因此,不調用任何save()方法在你的模型,也沒有發出pre_save或post_save信號(這是一個調用Model.save())的結果。該文件保存爲節省模型的一部分https://docs.djangoproject.com/en/1.8/topics/files/#using-files-in-models

雖然從文檔並不明顯,上傳的文件保存到磁盤作爲模型.save()的一部分,以及數據庫,因此在保存模型之前,不能依賴磁盤上使用的實際文件名。

這意味着您可以使用.update()直接更改存儲在數據庫列中的路徑值,但它假定該文件已保存到該位置的磁盤。

解決此問題的最簡單方法是在兩個路徑中都調用.save().create()已經呼籲.save()所以你需要到.update()版本改變爲一些諸如:

for key, value in update_data.items(): 
    setattr(instance.profile, key, value) 
instance.profile.save(update_fields=update_data.keys()) 
+0

什麼明確記載的答案,謝謝。 – Diesel