2012-07-25 96 views
2

我有下面的代碼後:編輯的Django模型保存它

models.py

class TelefoneIP(models.Model): 
     mac = models.CharField(max_length=12, help_text="Este campo deve ter 12 digitos") 
     modelo = models.ForeignKey(ModeloTelefoneIP) 
     cliente_atual = models.ForeignKey(Cliente) 
     fornecedor = models.ForeignKey(Fornecedor) 
     datacompra = models.DateField(verbose_name="Data de compra", null=True, blank=True) 
     nfcompra = models.IntegerField(verbose_name="Nota fiscal de compra") 

class MovimetoTelefoneIP(models.Model): 
     equipamento = models.ForeignKey(TelefoneIP) 
     cliente = models.ForeignKey(Cliente) 
     nfvenda = models.IntegerField(verbose_name="Nota fiscal de saída", null=True, blank=True) 
     datavenda = models.DateField(verbose_name="Data de saída", null=True, blank=True) 

admin.py:

class TelefoneIPInline(admin.StackedInline): 
     model = MovimetoTelefoneIP 
     extra = 1 
     list_filter = ['nome'] 

class TelefoneIPAdmin(admin.ModelAdmin): 
     list_display = ('mac', 'modelo', 'fornecedor',) 
     list_filter = ['cliente_atual__nome'] 
     search_fields = ['mac'] 
     inlines = [TelefoneIPInline] 

的問題是,當我編輯的內嵌,我可以在保存時將cliente_atual(在TelefoneIP上)的值設置爲客戶端(在MovimentoTelefoneIP上)?

謝謝。

PS:我在MovimentoTelefoneIP裏輸入了這段代碼,但是沒有工作。 更新了字段cliente_atual,但內聯數據沒有保存。 我也試過Hassek的代碼並沒有什麼..

def save(self, *args, **kwargs): 
      MovimetoTelefoneIP.save() 
      equipamento = self.equipamento 
      equipamento.cliente_atual = self.cliente 
      equipamento.save() 

回答

0

是的,你必須覆蓋從形式保存,並添加形式向管理員:

class TelefoneIpForm(forms.ModelForm): 
    class Meta: 
     model = TelefoneIp 

    def save(self, commit=True): 
     instance = super(TelefoneIpForm, self).save(commit=commit)   

     equipamento = instance.equipamento 
     equipamento.cliente = instance.cliente_atual 
     equipamento.save() 

class TelefoneIPAdmin(admin.ModelAdmin): 
    list_display = ('mac', 'modelo', 'fornecedor',) 
    list_filter = ['cliente_atual__nome'] 
    search_fields = ['mac'] 
    inlines = [TelefoneIPInline] 
    form = TelefoneIpForm 

我還沒有測試的代碼所以如果信息無法像代碼中顯示的那樣訪問,只需檢查調試對象pdb

+0

它沒有爲我工作.. – 2012-07-25 16:32:07

+0

你嘗試調試它嗎?它拋出了什麼異常? – Hassek 2012-07-25 16:40:32

+0

未綁定的方法save()必須使用MovimetoTelefoneIP實例作爲第一個參數調用(取而代之)。 我還發布了一個上面的代碼,工作50%。 – 2012-07-25 16:52:58