gpt4 book ai didi

python - “ForeignKey”对象没有属性

转载 作者:行者123 更新时间:2023-11-30 22:05:19 25 4
gpt4 key购买 nike

当我尝试为以下模型进行迁移时:

class Location(models.Model):
name = models.CharField(max_length=200)
latitude = models.FloatField
longitude = models.FloatField
altitude = models.IntegerField

def _str_(self):
return self.name

def getLatitude(self):
return self.latitude

def getLongitude(self):
return self.longitude

class Distance(models.Model):
placeA = models.ForeignKey(Location, on_delete=models.CASCADE)
placeB = models.ForeignKey(Location, on_delete=models.CASCADE)
placeAlatitude = placeA.getLatitude()
placeBlatitude = placeB.getLatitude()
placeAlongitude = Location.objects.select_related().get(placeA.longitude)
placeBlongitude = Location.objects.select_related().get(placeB.longitude)
distance = models.FloatField(default = 0.0)

我收到错误:

'ForeignKey' object has no attribute 'getLatitude'

如果我尝试直接访问纬度 (placeA.latitude),我会收到类似的错误

我做错了什么?我刚开始使用 Django 框架。

最佳答案

首先,您的 Location 中可能存在错误模型:您在这里构建 FloatFieldIntegerField :您只传递对该类的引用,而不是“调用”它。因此,为了定义这些列,您应该添加括号:

class Location(models.Model):
name = models.CharField(max_length=200)
latitude = models.FloatField<b>()</b>
longitude = models.FloatField<b>()</b>
altitude = models.IntegerField<b>()</b>

# ...

接下来你不能定义placeAlatitudeplaceA.GetLatitude() ,在类(class)级别placeAForeignKey对象,不是 Location ,对象,但是您可以定义 @property在这里,将是 Distance对象,获取相关对象的正确属性:

class Distance(models.Model):
placeA = models.ForeignKey(Location, on_delete=models.CASCADE)
placeB = models.ForeignKey(Location, on_delete=models.CASCADE)
distance = models.FloatField(default = 0.0)

@property
def <b>placeAlatitude</b>(self):
return self.placeA.latitude

@property
def <b>placeBlatitude</b>(self):
return self.placeB.latitude

@property
def <b>placeAlongitude</b>(self):
return self.placeA.longitude

@property
def <b>placeBlongitude</b>(self):
return self.placeB.longitude

关于python - “ForeignKey”对象没有属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53058631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com