2

我有以下代码:

模型.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)

管理员.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()
4

2 回答 2

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调试它的对象

于 2012-07-25T14:38:32.913 回答
0

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

于 2012-07-27T19:08:05.697 回答