保存后编辑Django模型

时间:2012-07-25 14:14:47

标签: python 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上)的值设置为cliente(在MovimentoTelefoneIP上)吗?

感谢。

PS:我在MovimentoTelefoneIP中输入了这段代码,但是也没有用。 字段cliente_atual已更新,但未保存内联数据。 我也试过Hassek的代码而没有......

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

2 个答案:

答案 0 :(得分: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

调试它的对象

答案 1 :(得分:0)

我找到了解决问题的另一种逻辑方法。但我仍有疑问:Access data from a related class in Django