Reputation: 262
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
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)
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='')
Upvotes: 2
Views: 2193
Reputation: 69
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.
Upvotes: 1