Leandro Abilio
Leandro Abilio

Reputation: 57

Access data from a related class in Django

I have the following code:

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'])]

I'd like to know if there is a way to use a field from MovimentoTelefoneIP that is a related class of TelefoneIP as a parameter in list_display, list_display or and in "fields" in actions.

Here's my models:

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)

Thanks.

Tried with Chris's answer:

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'])]

Upvotes: 0

Views: 315

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239440

Just create a method on your ModelAdmin that returns its value:

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'

You should probably add:

list_select_related = True

as well, so that it doesn't generate a query each time.

UPDATE

No, that's not correct. You want something like this:

 def get_clientes(self, obj):
    clientes = [m.cliente for m in obj.movimentotelefoneip_set.all()]
    return u', '.join(clientes)
 get_clientes.short_description = 'Clientes'

Upvotes: 2

Related Questions