2014-07-12 55 views
0

我想通過django模型從視圖中訪問,更新或創建數據庫中的新條目。Django:操縱模型

class UploadView(View): 

    def post(self, request): 
     file = request.FILES['file'] 
     data = request.POST['myObj'] 
     profile_id = request.POST['profile_id'] 
     profile = ProfileModel.objects.all().filter(pk=profile_id) 
     print (profile.id) 
     print(profile.details) 
     return HttpResponse('got post') 

和模型

class ProfileModel(models.Model): 
    ''' 
    ''' 
    id = models.AutoField(primary_key=True) 
    details = models.CharField(max_length=256)  
    file = models.BinaryField() 
    class Meta: 
     db_table = 'Profile' 

當它到達它拋出一個異常的print語句。

回答

2

profile是一個QuerySet不是個人檔案,所以如果你應該有你可以使用get方法

profile = ProfileModel.objects.get(pk=profile_id)

個人簡介它不應該有一個 id

get可以拋出DoesNotExist如果沒有匹配ProfileModel

+0

如果沒有匹配,我怎麼能創建一個新條目存在 – AlexandruC

+0

'get_or_create' django提供了很多建立在對模型文檔非常有幫助的方法,https://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create或者你可以嘗試「獲取」並在「DoesNotExist」上創建它。你也可以使用CBV中的djangso來創建一個工作流程來對你的對象執行CRUD操作 – dm03514

+0

好的,謝謝你,你對這個有什麼想法:http://stackoverflow.com/questions/24705246/django-存儲上傳文件到MySQL數據庫 – AlexandruC