本文介绍了TypeError:'RelatedManager'对象不可迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Django

我有下一个机型:

class Group(models.Model):
    name = models.CharField(max_length=100)
    parent_group = models.ManyToManyField("self", blank=True)

    def __unicode__(self):
        return self.name


class Block(models.Model):

    name = models.CharField(max_length=100)
    app = models.CharField(max_length=100)
    group = models.ForeignKey(Group)

    def __unicode__(self):
        return self.name

说,块 b1 g1 组。通过这个名字我想从 g1 组中获取所有块。我写了下面的递归函数:

say, block b1 has g1 group. By it's name I want to get all blocks from group g1. I wrote next recursive function:

def get_blocks(group):

    def get_needed_blocks(group):
        for block in group.block_set:
            blocks.append(block)

        if group.parent_group is not None:
            get_needed_blocks(group.parent_group)

    blocks = []
    get_needed_blocks(group)
    return blocks

b1.group.block_set 返回我 RelatedManager 对象,这是不可迭代的。

but b1.group.block_set returns me RelatedManager object, which is not iterable.

?怎么了?

推荐答案

尝试这样:

block in group.block_set.all()

这篇关于TypeError:'RelatedManager'对象不可迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 00:30