0

我有以下代码:

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

class TelefoneIPAdmin(admin.ModelAdmin):
        list_display = ('mac', 'modelo', 'fornecedor', )
        list_filter = ['cliente__nome']
        search_fields = ['mac']
        inlines = [TelefoneIPInline]
        actions = [export_as_csv_action("Exportar para Excel", fields=['mac','modelo','cliente'])]

我想知道是否有办法使用来自 MovimentoTelefoneIP 的字段,该字段是 TelefoneIP 的相关类,作为 list_display、list_display 或操作中的“字段”中的参数。

这是我的模型:

class TelefoneIP(models.Model):
        mac = models.CharField(max_length=12, help_text="Este campo deve ter 12 digitos")
        modelo = models.ForeignKey(ModeloTelefoneIP)
        cliente = models.ForeignKey(Cliente, verbose_name="Cliente Atual")
        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", blank=True, null=True)
        obs = models.TextField(max_length=500, null=True, blank=True)

class MovimentoTelefoneIP(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)

谢谢。

尝试了克里斯的回答:

class TelefoneIPAdmin(admin.ModelAdmin):
        cliente = MovimentoTelefoneIP.objects.all()
        list_display = ('mac', 'modelo','get_clientes')
        search_fields = ['mac']
        list_filter = ['get_clientes']
        def get_clientes(self, obj):
                clientes = [m.cliente for m in obj.MovimentoTelefoneIP_set.all()]
                return u', '.join(clientes)
        get_clientes.short_description = 'Clientes'
        inlines = [TelefoneIPInline]
        actions = [export_as_csv_action("Exportar para Excel", fields=['mac','modelo','fornecedor'])]
4

1 回答 1

2

只需在您的方法上创建一个ModelAdmin返回其值的方法:

list_display('get_related_field')
...
def get_related_field(self, obj):
    return obj.related_object.some_field
get_related_field.short_description = 'Some Field' # Column header
get_related_field.admin_order_field = 'related_object__some_field'

您可能应该添加:

list_select_related = True

同样,这样它就不会每次都生成查询。

更新

不,这是不正确的。你想要这样的东西:

 def get_clientes(self, obj):
    clientes = [m.cliente for m in obj.movimentotelefoneip_set.all()]
    return u', '.join(clientes)
 get_clientes.short_description = 'Clientes'
于 2012-07-27T18:41:58.293 回答