我想編寫一個模型方法,修改它的嵌套字段如何遍歷模型實例的多對一字段?
我在迭代通過與主模型相關的對象時遇到問題。特別的代碼是:
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'上迭代,您就知道自己做錯了。 –