Is there a way to save a tuple to a django model?
example:
Class User(models.Model):
location = models.tupleField()
where User.location = (longitude, latitude)
Maybe you are looking for GeoDjango's PointField :
from django.contrib.gis.db import models
Class User(models.Model):
location = models.PointField(help_text="Represented as (longitude, latitude)”)
Honestly, i didn't see tupleField in django documentation. I think better approach is add two fields longitude
and latitude
or create another model to store location and in User
model add ForeignKey
.
If you feel the need to save tuples in a single field, you should really look into relationships. That's the reason they were created.
Old answer:
This answer is assuming you're really saving locations.
If you're using PostgreSQL, you can use PostGIS . MySQL and Oracle has spacial fields built-in.
Django already supports Geo data. Eg -
from django.contrib.gis.db import models
class ModelName(models.Model):
centroid = models.GeometryField(blank=True, null=True)
Then you can make all sorts of geo queries(eg find places that are within a specified area, sorted by distance etc) and your DBMS will take care of them. Plus from that single field, you can access your data like -
lat, long = [modelobject.centroid.x, modelobject.centroid.y]
# Or you can just use .x or .y directly
You can read more about them in the Geodjango documentation .
我推荐Django-Geoposition应用程序,此外,您可以在 Google 地图中查看纬度和经度。
I think this answer could help here as well.
--
As @p14z suggests, the best way to save my tuple
was the ArrayField
. For my example, I just wanted to save a Polygon extent , with this format:
(3.7739613717694787, 50.31527681737183, 4.726162032377, 50.49743217278623)
from django.contrib.postgres.fields import ArrayField
my_tuple_field = ArrayField(models.FloatField(), size=4, null=True)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.