Edit/show Primary Key in Django Admin

后端 未结 6 975
时光取名叫无心
时光取名叫无心 2020-12-28 14:12

It appears Django hides fields that are flagged Primary Key from being displayed/edited in the Django admin interface.

Let\'s say I\'d like to input data in which I

相关标签:
6条回答
  • 2020-12-28 14:38

    To show the primary key, which by default will have a column name of "id" in the database - use "pk"

    def __str__(self):
        return '{} - {} ({})'.format(self.pk, self.name, self.pcode)
    
    0 讨论(0)
  • 2020-12-28 14:47

    The answer with the highest votes didn't work for me. I needed a getter.

    class StudentEnrollmentInline(admin.TabularInline):
        model = Enrollment
        readonly_fields=('student_enrollment_id',)
    
        def student_enrollment_id(self, obj):
            return obj.id
    

    Using django 1.11

    0 讨论(0)
  • 2020-12-28 14:48

    If you explicitly specify the primary key field in your models (with primary_key=True), you should be able to edit it in the admin.

    For Django models created via ./manage.py syncdb the following primary key field is added automatically:

    id = models.AutoField(primary_key=True)
    

    if you change (or add) that to your model explicitly as an IntegerField primary key, you'll be able to edit it directly using the admin:

    id = models.IntegerField(primary_key=True)
    

    But as others pointed out, this is a potential minefield...

    0 讨论(0)
  • 2020-12-28 14:51

    In django documentation, there is a short sentence about that, which is not clear:

    If neither fields nor fieldsets options are present, Django will default to displaying each field that isn't an AutoField and has editable=True, in a single fieldset, in the same order as the fields are defined in the model.

    Reason is, django do not allow you to edit an AutoField by any means (and that is the right thing since it is an auto increment value and should not be edited). @mnelson4's answer is a good approach to display it.

    0 讨论(0)
  • 2020-12-28 14:54

    It doesn't make sense to have an optional primary key. Either the PK is an autoincrement, in which case there's no need to edit it, or it's manually specified, in which case it is always required.

    Why do you need this?

    0 讨论(0)
  • 2020-12-28 14:55

    I also wanted to simply show the 'id' (primary key) within the Django admin, but not necessarily edit it. I just added it to the readonly_fields list, and it showed up fine. IE:

    class StudentEnrollmentInline(admin.TabularInline):
        model = Enrollment
        readonly_fields=('id',)
    

    whereas if I tried to add it to the 'fields' list, Django got upset with me, saying that field didn't exist...

    0 讨论(0)
提交回复
热议问题