我正在django上实现csv export。特别是我在我的模板上有一个链接来导出实际的查询,为此我试图在同一个基于类的视图上处理所有。
这是我的代码
@Resource
MyService myService;
@Resource
MyService myService2;
但是方法csv_output()是错误的..我得到这个TypeError:csv_output()接受0位置参数但是给出了1
我也尝试过使用classmethod装饰器,但没有成功。
我的问题是:如何从同一个类的另一个方法访问queryset变量?
答案 0 :(得分:0)
请注意self
中的get_queryset(self)
。这意味着此方法的第一个参数始终是类的实例(在您的情况下,MyView
)。所以当你想用另一种方法调用它时,你应该提供这个实例。
解决方案是将@staticmethod
装饰器替换为@classmethod
一个:
class MyView(ListView):
template_name = 'my_template.html'
model = Archivio
def get_queryset(self):
if self.request.GET.get('q'):
dateC = '01/01/' + self.request.GET.get('q')
queryset = Archivio.objects.filter(~Q(quoteiscrizione__anno_quota__exact=self.request.GET.get('q'))
return queryset
@classmethod
def csv_output(cls):
qs = cls.get_queryset(cls)
# Class methods have one required positional argument
# which is the class that contains them
# They are called like this:
# MyClass.class_method()
# So in your case, you can call
# get_queryset() by doing MyView.get_queryset()
# But as you are in a class method, you do
# cls.get_queryset()
# As get_queryset() needs one positional argument *self*,
# which is the instance of your class, you do
# cls.get_queryset(cls)
# and it will work as expected :-)
答案 1 :(得分:0)
我解决了我的问题,在请求中保存了我的查询集,然后在我的视图上使用它,如下所示:
views.py
class SomeClass(ListView):
def get_queryset(self):
.....
queryset = MyModel.objects.filter(*somefilterlist)
self.request.session['search_queryset'] = serialize('json', queryset) # in order to save something on session in must be JSON serialized
class Output(SomeClass):
@classmethod
def cvsOutput(cls):
deserialized = list(deserialize('json', request.session.get('search_queryset')))
pk_list = []
for arch in deserialized:
pk_list.append(arch.object.pk) # List of pk
queryset = Archivio.objects.filter(pk__in=pk_list) # Query the list ok pk's
通过这种方式,我能够提供ListView查询集的列表ok pk,然后根据pk的列表重新生成相同的查询..