2015-05-06 16 views
0

我有一個Mixin,允許我更新我已經創建的對象,事情是,我有太多的模型和每個不同的領域,這Mixin時,未找到對象返回一個404,我需要什麼時候找不到對象返回表單,用於創建與predio_id對象關聯的對象,我試過用get_object_or_create,但是用這種方法我必須通過每個字段。怎樣才能實現當對象沒有找到時,返回他對應的空表單來創建它?get_object_or_create在不同的模型mixin

class UpdateModelMixin(object): 
    def get_object(self): 
     return get_object_or_404(self.model,predio_id=self.kwargs['predio_id']) 

,這就是所謂來查看像這樣的:

class ManejoGeneralUpdateView(UpdateModelMixin, UpdateView): 
    model = ManejoGeneral 
    form_class = FormManejoGeneral 
    success_url = '/' 
    template_name = 'manejo_finca/edit/manejo_general.html' 

請注意,我在這裏寫下的更新視圖僅僅是近30°40更新視圖,我有一個,因爲每個的UpdateView調用不同的形式和模板

回答

0

這是非常簡單的,因爲get_or_create返回一個元組,只需添加[0]在查詢的末尾:

class UpdateModelMixin(object): 
    def get_object(self): 
     return Persona.objects.get_or_create(predio_id=self.kwargs['predio_id'])[0]