开发者

Edit/show Primary Key in Django Admin

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 may or may not want to specify a primary key. How would I go about displaying primary keys in the admin interface, and how could I make spe开发者_Python百科cifying it optional?


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...


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...


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)


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?


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜