用户模型中有150k条目。当我在没有raw_id_fields的django-admin中使用它时,在将所有条目作为外键的选择菜单加载时导致问题。是否有其他方式可以轻松加载或可以搜索?
我有如上定义的这些模型,并且在ProfileRecommendation模型中有一个用作ForeignKey的User模型。用户模型的数据库条目包含大约150k个条目。我不希望这些外来字段的默认选择选项。相反,如果可以过滤掉它们并只加载用户表的几个条目。如何使它们像自动完成建议一样可以搜索?
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='')
答案 0 :(得分:1)
您可以使用方法formfield_for_foreignkey
类似的东西:
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)
或其他方式是覆盖该modeladmin类的表单
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
您可以更改小部件并使用自动完成和ajax选择类似的内容。