TypeError: 'ManyRelatedManager' object is not iterable我在 Django 3.0 中遇到錯誤這是我的問題:我必須Collection與模型Element建立關系ManyToMany。這是模型(我顯然省略了與問題無關的所有其他屬性和方法):class Collection(models.Models): elements = models.ManyToManyField(Element, related_name="collections") @proprety def total_elements_value(self): total = 0 for element in self.elements.all(): # The problem is on this line ! total += element.total_value return totalclass Element(models.Models): value1 = models.IntegerField() value2 = models.IntegerField() @proprety def total_value(self): return self.value1 + self.value2但是當我嘗試調用 Collection.total_elements_value 屬性時,出現了這個錯誤:TypeError: 'ManyRelatedManager' 對象不可迭代我不明白。self.elements.all() 返回一個列表作為查詢集,所以它應該是可迭代的,不是嗎?當我在 python shell 中嘗試這個時,它工作正常:c = Collection.objects.all()[0]total = 0for element in c.elements.all(): total += element.total_valuereturn total # Works但不是當我打電話給物業時:c = Collection.objects.all()[0]c.total_elements_value # Throws the error我想知道如何解決這個問題,但更重要的是,了解為什么這不起作用。感謝您的幫助。
添加回答
舉報
0/150
提交
取消