raw_id_fields: How to show a name instead of id?

前端 未结 4 1589
北恋
北恋 2020-12-13 18:58

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 i

相关标签:
4条回答
  • 2020-12-13 18:59

    For the representation of an object use __unicode__

    class Person(models.Model):
        first_name = models.CharField(max_length=50)
        last_name = models.CharField(max_length=50)
    
        def __unicode__(self):
            return u'%s %s' % (self.first_name, self.last_name)
    

    In Python 3 use

    def __str__(self):
    
    0 讨论(0)
  • 2020-12-13 19:09

    I've also researched this and I don't think it's possible. I think the best you can do is display the unicode of the field next to the raw id field: http://djangosnippets.org/snippets/2108/

    Alternatively, you can display the unicode and a link to the value's corresponding admin change page: http://djangosnippets.org/snippets/2217/

    0 讨论(0)
  • 2020-12-13 19:16

    It seems this plugin: https://github.com/lincolnloop/django-dynamic-raw-id

    does what you want:

    (copied from the doc):

    Usage

    To start using django-dynamic-raw-id in your application all you need to do is implement DynamicRawIDMixin in your ModelAdmin class and add the desired fields to a list of dynamic_raw_id_fields:

    from dynamic_raw_id.admin import DynamicRawIDMixin
    
    class UserProfileAdmin(DynamicRawIDMixin, admin.ModelAdmin):
        dynamic_raw_id_fields = ('user',)
    

    You can use dynamic_raw_id widgets in a Admin filter as well:

    from dynamic_raw_id.admin import DynamicRawIDMixin
    from dynamic_raw_id.filters import DynamicRawIDFilter
    
    class UserProfileAdmin(DynamicRawIDMixin, admin.ModelAdmin):
        list_filter = (
            ('dynamic_raw_id_fk', DynamicRawIDFilter),
        )
    
    0 讨论(0)
  • 2020-12-13 19:23

    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

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