我有这3个型号:
class MyFile(models.Model):
file = models.FileField(upload_to="files/%Y/%m/%d")
def __unicode__(self):
"""."""
return "%s" % (
self.file.name)
class ExampleModel(models.Model):
attached_files =models.ManyToManyField(MyFile)
main_model = models.ForeignKey(MainModel)
class MainModel(models.Model):
attached_files =models.ManyToManyField(MyFile)
我的admin.py
如下:
class ExampleModelAdminInline(admin.TabularInline):
model = ExampleModel
extra = 2
class MainModelAdmin(admin.ModelAdmin):
inlines = [ExampleModelAdminInline]
我正在使用django-grapelli
,因为它为多个字段提供自动完成查找功能。但是,我不知道如何将此自动完成查找添加到TabularInline
管理员。任何人都可以解释一下如何设置attached_files
字段以进行自动完成查找吗?
答案 0 :(得分:1)
首先,您需要在output_shape
中设置要搜索的autocomplete_search_fields()
中的静态方法Model
。MyFile
。从我们得到的docs:
class MyFile(models.Model):
#your variable declaration...
@staticmethod
def autocomplete_search_fields():
return ("id__iexact", "name__icontains",) #the fields you want here
您还可以定义GRAPPELLI_AUTOCOMPLETE_SEARCH_FIELDS
来代替声明静态方法,例如:
GRAPPELLI_AUTOCOMPLETE_SEARCH_FIELDS = {
"myapp": {
"MyFile": ("id__iexact", "name__icontains",)
}
}
然后,您应该将查找和原始字段添加到所需的admin
课程中,考虑其相关的Model
(例如,您的ExampleModel
),其中ManyToManyField
}}。您也可以以类似的方式处理ForeignKey
。也来自上述文件:
class ExampleModel(models.Model):
main_model = models.ForeignKey(MainModel) #some FK to other Model related
attached_files =models.ManyToManyField(MyFile) #the one with static decl
class MainModelAdmin(admin.ModelAdmin):
#your variable declaration...
# define raw fields
raw_id_fields = ('main_model','attached_files',)
# define the autocomplete_lookup_fields
autocomplete_lookup_fields = {
'fk': ['main_model'],
'm2m': ['attached_files'],
}
请记住将关系的两端(您的模型)注册到admin.site
,如下所示:
#the one with the m2m and the one with the lookup
admin.site.register(ExampleModel, MainModelAdmin)
您还可以查看this问题,以便更好地了解。