Django: How to Display the Foreign Key Value in Admin Form

advertisements

How do I get the admin form to display the foreign key value in the drop down list of a django admin form rather than display 'table name object'? I am struggling to work this out.

Here are examples of my model code (Both contain the catname field. catname is PK in Parent and FK in Child).

Parent(models.Model):
catname = models.CharField(db_column='catname', primary_key=True, max_length=255, verbose_name="catname")
description = models.CharField(db_column='Description', max_length=255, blank=True, null=True)

class Meta:
    managed = False
    db_table = 'Parent'
    verbose_name_plural = ('Parent')

    #def __unicode__(self): return self.catname.catname
    def __str__(self):
        return '%s' % (self.catname)

class Child(models.Model):
    description = models.CharField(db_column='VarDescription', max_length=255, blank=True, null=True)
    cname = models.CharField(db_column='VarName', primary_key=True, max_length=255)
    catname = models.ForeignKey(Parent, db_column='catname', blank=True, null=True)
    def __unicode__(self):
        return self.name
    def child_cat(self):
        return self.catname.catname
    class Meta:
        managed = False
        db_table = 'Child'
        verbose_name_plural = ('Child')

Admin looks like:

from django.contrib import admin

from Library.models import Parent, Child
# Register your models here.

class ChildAdmin(admin.ModelAdmin):
    list_display = ('cname','description','child_cat')
    fields=('cname','description','child_cat')
    search_fields = ('cname','description')
    ordering = ('cname',)

admin.site.register(Child,ChildAdmin)


You can override the form used by ModelAdmin or even change just one field with ModelAdmin.formfield_overrides.

Read the documentation here