Reputation: 103
When I try to make migrations for the following models:
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)
I am getting the error:
'ForeignKey' object has no attribute 'getLatitude'
I get a similar error if I try to directly access the latitude directly (placeA.latitude
)
What am I doing wrong? I am new to using the Django framework.
Upvotes: 2
Views: 10206
Reputation: 477814
First of all there is likely an error in your Location
model: you here do not construct the FloatField
s and IntegerField
: you only pass a reference to the class, you do not "call" it. So in order to define these columns, you should add parenthesis:
class Location(models.Model):
name = models.CharField(max_length=200)
latitude = models.FloatField()
longitude = models.FloatField()
altitude = models.IntegerField()
# ...
Next you can not define placeAlatitude
, etc. with placeA.GetLatitude()
, at class level placeA
is a ForeignKey
object, not a Location
, object, you can however define a @property
here that will, for a Distance
object, fetch the correct attribute of the related objects:
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 placeAlatitude(self):
return self.placeA.latitude
@property
def placeBlatitude(self):
return self.placeB.latitude
@property
def placeAlongitude(self):
return self.placeA.longitude
@property
def placeBlongitude(self):
return self.placeB.longitude
Upvotes: 7
Reputation: 1608
In your model, you are defining the structure. You can't use
placeAlatitude = placeA.getLatitude()
placeBlatitude = placeB.getLatitude()
placeAlatitude and placeBlatitude must be define the type of model. You can't simply return value.
From analyzing your model these two fields are not necessary it is redundant values(same case for placeAlongitude and placeBlongitude). You defined a foreign key relation to location. So you can access longitude and latitude by using that relation.
Upvotes: 1