如何在django-import-export中从ModelResource的方法queryset获取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
答案 0 :(得分:2)
我正在寻找类似的东西。我希望基于管理员要导出的请求将请求对象附加到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
答案 1 :(得分:1)
问题解决了。我忘记了以前在我的观点中曾打过people_resource.export()
。现在更容易了,因为我只在方法export()
中传递了variabel kwargs并在模型def export()
中覆盖了PeopleResource
。所以我的解决方案在这里。
views.py
def export_excel(request):
...
people_resource = PeopleResource()
dataset = people_resource.export(agent=request.user.agent,)
...
models.py
class PeopleResource(ModelResource):
class Meta:
model = People
exclude = ('id','agent', 'public_id', 'active')
...
...
def export(self, queryset=None, *args, **kwargs):
queryset = People.objects.filter(agent=kwargs['agent'])
return super(PeopleResource, self).export(queryset, *args, **kwargs)
答案 2 :(得分:0)
导出自定义数据对我来说是这样的:
from django.contrib import admin
from import_export.admin import ExportMixin
from import_export.resources import ModelResource
from jobs.models import Job
class JobResources(ModelResource):
class Meta:
model = Job
fields = ('id', 'foo', 'bar')
class JobAdmin(ExportMixin, admin.ModelAdmin):
resource_class = JobResources
fieldsets = (...)
祝大家好运!