Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

python - raw_id_fields: How to show a name instead of id?

Customizing a Django Admin panel, I'm using raw_id_fields to select a ForeignKey from a Model which has thousands of elements, because the default select-box drop-down is inconvenient with so many elements.

It works but it shows the id as can be seen on this image: enter image description here

Is there any way to show the name or other field instead of the id? Or, is there any better way to accomplish this than using raw_id_fields?

This is my code in models.py:

class Structure(MPTTModel):
    name = models.CharField(max_length=200, unique=True, verbose_name = _('name'))
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children', verbose_name = _('parent'))

    def __unicode__(self):
        return u"%s" % (self.name)

In admin.py:

class StructureAdmin(tree_editor.TreeEditor):
    search_fields = ('name',)
    raw_id_fields = ('parent',)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From Django 2.0 you can use autocomplete_fields. It will work just like ajax select2.

In admin.py

class StructureAdmin(tree_editor.TreeEditor):
    search_fields = ('name',)
    autocomplete_fields = ('parent',)

Reference: https://docs.djangoproject.com/en/2.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.autocomplete_fields


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...