Skip to content

Instantly share code, notes, and snippets.

@roddds
Created July 27, 2015 00:12
Show Gist options
  • Save roddds/2d9ab4238ad5f02d3483 to your computer and use it in GitHub Desktop.
Save roddds/2d9ab4238ad5f02d3483 to your computer and use it in GitHub Desktop.
Showing foreign key attributes on Django Admin
from django.contrib import admin
from django.core.urlresolvers import reverse
from .models import Carro, Fabrica, Pais
class CarroAdmin(admin.ModelAdmin):
list_display = ('nome', 'fabrica', 'pais')
def queryset(self):
qs = super(CarroAdmin, self).queryset()
return qs.select_related('fabrica__pais__codigo', 'fabrica__pais__id')
def pais(self, obj):
pais_edit_url = reverse(
'admin:cars_pais_change',
args=(obj.fabrica.pais.id,))
return '<a href="{url}">{codigo}</a>'.format(
url=pais_edit_url,
codigo=obj.fabrica.pais.codigo)
pais.allow_tags = True
pais.short_description = 'Codigo do pais'
pais.admin_order_field = 'fabrica__pais__codigo'
class Meta:
model = Carro
admin.site.register(Carro, CarroAdmin)
admin.site.register(Fabrica)
admin.site.register(Pais)
from django.db import models
class Pais(models.Model):
nome = models.CharField(max_length=30)
codigo = models.CharField(max_length=2)
class Meta:
verbose_name_plural = 'Paises'
def __unicode__(self):
return self.nome
class Fabrica(models.Model):
nome = models.CharField(max_length=30)
pais = models.ForeignKey('cars.Pais')
def __unicode__(self):
return self.nome
class Carro(models.Model):
nome = models.CharField(max_length=30)
fabrica = models.ForeignKey("cars.Fabrica")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment