python - Django Grappelli 在内联管理中添加自动完成查找

标签 python django autocomplete django-grappelli

我有这 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字段进行自动完成查找?

最佳答案

首先,您需要在要搜索的 Model 中设置静态方法 autocomplete_search_fields(),在您的情况下是 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问题以便更好地理解。

关于python - Django Grappelli 在内联管理中添加自动完成查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44684003/

相关文章:

python - 如何使用 python 和 opencv 查找图像的 pca?

python - 故障转移选项在 mysql.connector 中抛出错误

python - 无法在 conda meta.yaml 文件中指定 pip 依赖项

python - Django 管理器不可用; 'auth.User' 已被交换为 'users.MyUser'

javascript - JQuery 自动完成以一个字符串返回所有结果

python - 用 Python Boost 包装 C++ operator()

python - 检查 Django 模板中的请求获取参数

python - 我可以使用带有字符串连接的 Django F() 对象吗?

javascript - React Material UI 从自动完成中打开模式失去焦点

bash - 在命令行上获取 git-commit-ids