我想编写一个模型方法,修改它的嵌套字段如何遍历模型实例的多对一字段?
我在迭代通过与主模型相关的对象时遇到问题。特别的代码是:
def set_si_units(self):
self.currently.get_si_units()
for i in range(0, self.hourly.data.count()):
self.hourly.data[i].get_si_units()
修饰self.currently
运行顺利的第二线和我接收转换后的温度。 for循环但是给了我以下错误:
TypeError: 'RelatedManager' object does not support indexing
我真的希望能够通过Data
模型的每个实例单独进行迭代,所以我可以转换的温度,因为我与Currently
模型做。
我在下面也包含了相关的代码。如果您需要查看其他内容,请告诉我。任何关于我的方法的帮助或反馈非常感谢!
回溯
File "/path_to_project/project/weather/models.py", line 137, in get_si_units
self.hourly.data[i] = self.hourly.data[i].get_si_units()
TypeError: 'RelatedManager' object does not support indexing
中的类get_si_units()(例如,目前&数据)
class SomeClass(model.Models):
temperature = models.FloatField(null=True, blank=True)
... # Other fields
def convert_f_to_c(self, temperature_f):
...
def get_si_units(self):
data_point = self
data_point.temperature = self.convert_f_to_c(self.temperature)
... # Convert other fields
return data_point
位置类,我卡在
class Location(models.Model):
currently = models.OneToOneField(Currently, on_delete=models.CASCADE)
hourly = models.OneToOneField(Hourly, on_delete=models.CASCADE)
...
def set_si_units(self):
self.currently.get_si_units()
for i in range(0, self.hourly.data.count()):
self.hourly.data[i].get_si_units()
通常在Python中,如果您发现自己在大小范围的'range'上迭代,您就知道自己做错了。 –