ForeignKey Field in django admin

家住魔仙堡 提交于 2020-01-04 11:01:53

问题


There are around 1.5 lakhs entry in User model. So when i am using it in django-admin without the raw_id_fields it is causing problem while loading all the entry as a select menu of foreign key. is there alternate way so that it could be loaded easily or could become searchable.

Basically i have these models as of defined above and there is a User model which is used as ForeignKey in ProfileRecommendation models. so the database entry for user model consist of around 1,50,000 entries. I don't want default select option for these foreign fields. Instead if can filter them out and load only few entries of the user table. Or anyhow i can make them searchable like autocomplete suggestion

admin.py

class ProfileRecommendationAdmin(admin.ModelAdmin):
    list_display = ('user', 'recommended_by', 'recommended_text')
    raw_id_fields = ("user", 'recommended_by')
    search_fields = ['user__username', 'recommended_by__username', ]
    admin.site.register(ProfileRecommendation, ProfileRecommendationAdmin)

models.py

class ProfileRecommendation(models.Model):
    user = models.ForeignKey(User, related_name='recommendations')
    recommended_by = models.ForeignKey(User, related_name='recommended')
    recommended_on = models.DateTimeField(auto_now_add=True, null=True)
    recommended_text = models.TextField(default='')

回答1:


I recommend you using django-select2-forms

Using that package, you can define your model foreign field as below:

from select2.fields import ForeignKey

class Author(models.Model):
  name = models.CharField(max_length=100)
  active = models.BooleanField()

class Entry(models.Model):
    author = ForeignKey(Author,
    limit_choices_to=models.Q(active=True),
    ajax=True,
    search_field='name',
    overlay="Choose an author...",
    js_options={
        'quiet_millis': 200,
    },
    on_delete=models.CASCADE)

In django admin this will load authors' names using ajax, which should work much faster than using default admin ForeignKey field. Also as you can see from example, you can use limit_choices_to for filtering only needed values available for selection.

If not django-select2-forms, you can play with any other package available for django autocomplete: list of autocomplete packages here

I tried few from the list, but django-select2-forms looks like the best for me.



来源:https://stackoverflow.com/questions/39441421/foreignkey-field-in-django-admin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!