Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: foreign key value in a list display admin

I'm trying to display the foreign key 'company name' in the admin list view. However, the list view just shows (None) for the company. What I'm I doing wrong?

admin.py

class CampaignAdmin(admin.ModelAdmin):
    #fields = ['name', 'Company_name', 'active', 'modified', 'created']
    list_display = ['name', 'related_company', 'active', 'modified', 'created']
    list_filter = ['active']
    search_fields = ['name']
    sortable_field_name = "name"
    autocomplete_lookup_fields = {
        'name': ['name'],
        }

    def related_company(self, obj):
        return '%s'%(obj.Company.name)
    related_company.short_description = 'Company'


admin.site.register(Campaign, CampaignAdmin)

model.py

class Company(models.Model):
    companyid = models.CharField(max_length=255, primary_key=True, db_column='companyID')
    name = models.CharField(max_length=105)
    logourl = models.CharField(max_length=255, db_column='logoURL')
    website = models.CharField(max_length=255, blank=True)
    active = HibernateBooleanField(default=False)
    created = models.DateTimeField()
    modified = models.DateTimeField(null=True, blank=True)

    class Meta:
        db_table = u'company'
        ordering = ['name']

    @staticmethod
    def autocomplete_search_fields():
        return ("id__iexact", "name__icontains",)

    def __unicode__(self):
        return self.name


class Campaign(models.Model):
    campaignid = models.CharField(max_length=255, primary_key=True, db_column='campaignID')
    name = models.CharField(max_length=105)
    active = HibernateBooleanField(default=False)
    created = models.DateTimeField()
    modified = models.DateTimeField(null=True, blank=True)
    companyid = models.ForeignKey(Company, null=True, db_column='companyID', blank=True)

    class Meta:
        db_table = u'campaign'


    def __unicode__(self):
        return self.name
like image 760
Prometheus Avatar asked Jan 02 '13 22:01

Prometheus


People also ask

What is Admin ModelAdmin in Django?

One of the most powerful parts of Django is the automatic admin interface. It reads metadata from your models to provide a quick, model-centric interface where trusted users can manage content on your site. The admin's recommended use is limited to an organization's internal management tool.


1 Answers

Your Campaign model has no Company attribute - the ForeignKey is the field companyid. You'd need to change your function to

def related_company(self, obj):
    return obj.companyid.name
related_company.short_description = 'Company'

And since the __unicode__() method of the company object returns the name anyway, you probably don't need the custom function anyway - I think you can put the foreign key field directly in the display list:

list_display = ['name', 'companyid', 'active', 'modified', 'created']
like image 102
Blair Avatar answered Oct 18 '22 04:10

Blair