In the class Vessel, there are three model fields to enter a float value represented in Meters. I want to use the function below to convert that value to Feet, and display both Meters and Feet values. How do I convert the FloatField value to a float type?
length_meters = models.FloatField(null=True, blank=True)
beam_meters = models.FloatField(null=True, blank=True)
draft_meters = models.FloatField(null=True, blank=True)
#Function to convert meters to feet
CONVERT_NUM = 3.281
feet = meters * CONVERT_NUM
#TODO - do a sql query to get the float value from FloatField value?
length_feet = metersToFeet(float(length_meters))
beam_feet = metersToFeet(float(beam_meters))
draft_feet = metersToFeet(float(draft_meters))
From the docs for
A floating-point number represented in Python by a
There’s no conversion necessary.
Error received with float() in place:
TypeError: float() argument must be a string or a real number, not 'FloatField'
Error received when removing the float() method:
TypeError: unsupported operand type(s) for *: 'FloatField' and 'float'
The root cause of that error is that you’re trying to perform the operation on the field, and not on the data within that field.
Vessel is a class. The FloatField objects are attributes of the class.
When you’re performing operations on those attributes, you need to identify which instance of the class is being operated on.
For the rest of the code you’ve posted here, it’s not clear where you’re trying to use this.
In the case of your
metersToFeet function, if it’s defined as a method on that class, it is going to receive that instance (usually called
self) as the first parameter of that function. This means it’s definition should look like
def metersToFeet(self, meters):
Finally, these lines:
Are not going to do what you think you want to do if they’re also located within the class.
Have you worked your way through either the Official Django Tutorial or the Django Girls Tutorial? If not, I would strongly recommend it. It teaches you a lot about working with Models.
Also, you may wish to review the Python docs at 9. Classes — Python 3.11.3 documentation