remove the default select in ForeignKey Field of django admin

心已入冬 提交于 2019-12-25 04:25:44

问题


There are 150k entries in User model. When i am using it in django-admin without the raw_id_fields it is causing problem while loading all the entries as a select menu of foreign key. is there alternate way so that it could be loaded easily or could become searchable?

I have these models as of defined above and there is a User model which is used as ForeignKey in ProfileRecommendation models. The database entry for user model consist of around 150k 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. How 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:


you can use method formfield_for_foreignkey

something like this:

class ProfileRecommendationAdmin(admin.ModelAdmin):


   def formfield_for_foreignkey(self, db_field, request, **kwargs):
     if db_field.name == "user":
       kwargs["queryset"] = User.objects.filter(is_superuser=True)
     return super(ProfileRecommendationAdmin,self).formfield_for_foreignkey(db_field, request, **kwargs)

or other way is to override the form for that modeladmin class

from django import forms
from django.contrib import admin
from myapp.models import Person

class PersonForm(forms.ModelForm):

    class Meta:
        model = Person
        exclude = ['name']

class PersonAdmin(admin.ModelAdmin):
    exclude = ['age']
    form = PersonForm

you can change the widget and use something like the selectize with autocomplete and ajax.



来源:https://stackoverflow.com/questions/39497185/remove-the-default-select-in-foreignkey-field-of-django-admin

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