Making Django admin display the Primary Key rather than each object's Object type

前端 未结 3 1190
耶瑟儿~
耶瑟儿~ 2021-02-04 11:43

In Django 1.1 admin, when I go to add or change an object, my objects are displayed as:

Select host to change
    * Add host

    Host object
    Host object
            


        
3条回答
  •  别那么骄傲
    2021-02-04 12:11

    Add a __unicode__() method to Host. To show the primary key of your host objects, you'd want something like:

    class Host(models.Model):
        host = models.CharField(max_length=100, primary_key=True)
    
        def __unicode__(self):
            return self.pk
    
        ...
    

    You might want to think about showing the contents of the host field:

    class Host(models.Model):
        host = models.CharField(max_length=100, primary_key=True)
    
        def __unicode__(self):
            return self.host
    
        ...
    

    You'll need to do something similar for every model you've got.

    For Python 3 compatibility, you'll want to do something like this (see the documentation):

    from __future__ import unicode_literals
    from django.utils.encoding import python_2_unicode_compatible
    
    @python_2_unicode_compatible
    class Host(models.Model):
        host = models.CharField(max_length=100, primary_key=True)
    
        def __str__(self):
            return self.host
    
        ...
    

提交回复
热议问题