modelformset __iter__重载问题 [英] modelformset __iter__ overloading problem

查看:54
本文介绍了modelformset __iter__重载问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写自定义模型格式集。我需要将该表单按字段排序的值排序。我在子表单集类中重载了BaseFormSet的 __ iter __ 方法。

I'm writing the custom modelformset. I need that forms to be sorted by value of field "ordering". I overloaded __iter__ method of BaseFormSet in my child formset class.

class SortedCatForms(BaseFormSet):
    def __iter__(self):
        return iter(self.forms.sort(
                            key=lambda form: form['ordering'].value())) #line 38, the problem line.

    def __getitem__(self, index):
        return list(self)[index]



我在我的modelformset中使用它:



I use it in my modelformset:

OrderCatsFormSet = modelformset_factory(ParentCategory,
                                    fields=('category', 'ordering'),
                                    formset=SortedCatForms,
                                    extra=0)



问题是:



The problem is:


呈现时发生TypeError错误: NoneType对象不可迭代

Caught TypeError while rendering: 'NoneType' object is not iterable

异常位置:... forms.py在 __ iter __ ,第38行

Exception Location: ...forms.py in __iter__, line 38

但是在源BaseFormSet中:

But in source BaseFormSet:

def __iter__(self):
    """Yields the forms in the order they should be rendered"""
    return iter(self.forms)

我的代码有什么问题?

完整追溯

在@bobince的建议下,我的代码变成了: / p>

After @bobince's advice my code became this:

class SortedCatForms(BaseFormSet):
def __iter__(self):
    return iter(
            sorted(self.forms, key=lambda form: form['ordering'].value()))

def __getitem__(self, index):
    return list(self)[index]

它返回没有表格的空列表。 __ getitem __ 是否有问题?

It's returns empty list without forms. Are problem in __getitem__?

推荐答案

对Django不够熟悉,无法判断是否是正确的方式,但这是一个简单的陷阱:

Not familiar enough with Django to judge whether this is the right way, but here's a simple gotcha:

return iter(self.forms.sort( ...

sort()是列表上的一种方法,该方法对它进行就地排序并返回 None 。您可能是说:

sort() is a method on a list that sorts it in-place and returns None. You probably meant:

return iter(sorted(self.forms, ...

这篇关于modelformset __iter__重载问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆