1👍
✅
There are a couple of approaches you could take. The approach you choose might depend on whether this is a "one-off" or if you need a reusable class. I would probably favour ‘method 2’.
Method 1
You could filter the queryset in your view, and then pass this to export:
def export_students(request):
queryset = Students.objects.filter(school = kwargs['school'], klass = kwargs['klass'])
# notice that the first arg to the Resource is a Queryset
dataset = ExportStudentsResource().export(queryset)
Method 2
Override the get_queryset()
method on your resource. You can set args at instantiation and have them apply to the query:
class ExportStudentsResource(resources.ModelResource):
def __init__(self, **kwargs):
self.school = kwargs['school']
self.klass = kwargs['klass']
def get_queryset(self):
return Students.objects.filter(school=self.school, klass=self.klass)
If you look at the source for export()
it should make it clearer what is going on, and how this fits together.
Source:stackexchange.com