python - 如何在 ModelResource django-import-export 中获取请求

标签 python django python-3.x django-import-export

如何从 django-import-export 中 ModelResource 的方法查询集中获取 request.user?

class PeopleResource(ModelResource):
    class Meta:
       model = People
       exclude = ('id','agent', 'public_id', 'active')

    def dehydrate_placeA(self, people):
        ...
        ...

    def get_queryset(self):
        query = People.objects.filter( ..... request.user )
        return query

最佳答案

我正在寻找类似的东西。我希望请求对象(基于在 admin 中发出的要导出的请求)附加到 Resource 实例,以便我可以检查它并根据查询参数动态影响功能。如果您想根据用户动态更改它,这也将非常有用。结果很简单:

首先,继承 ModelResource 类并寻找新的 kwarg:

from import_export import resources

class RequestModelResource(resources.ModelResource):
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(RequestModelResource, self).__init__(*args, **kwargs)

然后,在 import-export 中有一个相关的管理方法,您可以使用它来传递 kwargs。 See here .将此添加到继承自 import_export.admin.ImportExportModelAdmin 的 ModelAdmin :
class MyModelAdmin(ImportExportModelAdmin):
    resource_class = MyModelResource

    def get_resource_kwargs(self, request, *args, **kwargs):
        """ Passing request to resource obj to control exported fields dynamically """
        return {'request': request}

基本上就是这样。现在可以在从 RequestModelResource 继承的 Resource 类中的任何位置使用请求。例如:
class MyModelResource(RequestModelResource):
    def get_export_fields(self):
        fields = super().get_fields()

        # Check self.request.user, self.request.GET, etc to impact logic
        # however you want!

        return fields

关于python - 如何在 ModelResource django-import-export 中获取请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51570074/

相关文章:

python - numpy 数组的缓存装饰器

python - 在 click python 模块中的命令后获取参数

python - Django 后端中立的 DictCursor

python - 将Python 3转换为autodoc可以读取的 "simple"python

python - 阅读 Python 文档对初学者学习 Python 好吗?

python - 如何在 python 结构中提供公钥密码短语

python - Django 日志记录项目和应用程序命名空间

python - django 模型类是单例/仅实现一次吗?

python - 具有多个属性的 Django 查询

python - PyCharm 无法识别以开发模式安装的模块