Django admin List Display + ForeignKey = Empty Cha

2019-02-13 10:33发布

问题:

I've got a weird problem in django admin list_display. Whenever I add a foreign key to a list_display the whole change list view goes blank showing only the total no of entries.

models.py:

class Organization(models.Model):
    org_id = models.AutoField(primary_key=True)
    org_name = models.CharField(max_length=288)

    def __unicode__(self):
        return self.org_name

    class Meta:
        db_table = u'organization'

class Server(models.Model):
    server_id = models.AutoField(primary_key=True)
    server_name = models.CharField(max_length=135,verbose_name="Server Name")
    org = models.ForeignKey(Organization,verbose_name="Organization")   

    def __unicode__(self):
        return self.server_name

    class Meta:
        db_table = u'server'

admin.py:

class ServerAdmin(admin.ModelAdmin):
    list_display = ('server_name','org') 
admin.site.register(Server,ServerAdmin) 

Now I'd expect this code to show me the organization name in the ChangeList View, But instead I get this:

If I remove the org in the list_display of ServerAdmin class, I get this:

I didn't modify the template or override any ModelAdmin methods. I'm using Mysql(5.1.58) as my database that comes with ubuntu 11.10 repository.

I'll be really glad if I could a get a sloution for this problem guys. Thanks in advance.

回答1:

I second Stefano on the fact that null=True, blank=True is to be added. But, I think you only need to add it to the org_name field of the Organization model. That should make your way through. It has to be done because you have run inspectdb to create models from your legacy DB. And probably the organization table in the DB has an empty string stored. So, adding the above would allow the Admin to have a blank field/column displayed.

Moreover, you can also try using callbacks in situations where you don't want to make changes to your model definition like the above.



回答2:

Try adding null=True, blank=True to all your model fields.

Usually django admin will silenty fail (thus show no records in the list) if the row does not validate the model constraints.



回答3:

See: https://stackoverflow.com/a/163968/1104941

Does the following work for you?

admin.py:

class ServerAdmin(admin.ModelAdmin):
    list_display = ('server_name','org__org_name') 
admin.site.register(Server,ServerAdmin) 


回答4:

I had a similar problem and solved it like this (using your example):

class ServerAdmin(admin.ModelAdmin):
    list_display = ('server_name', 'get_org') 

    def get_org(self, obj):
        return obj.org.org_name

    get_org.short_description = 'Org'

admin.site.register(Server,ServerAdmin)