简体   繁体   English

将元组保存到 Django 模型

[英]save a tuple to a django model

Is there a way to save a tuple to a django model?有没有办法将元组保存到 Django 模型?

example:例子:

Class User(models.Model):
  location = models.tupleField()

where User.location = (longitude, latitude)其中User.location = (longitude, latitude)

Maybe you are looking for GeoDjango's PointField :也许您正在寻找GeoDjango 的 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.老实说,我在 Django 文档中没有看到 tupleField。 I think better approach is add two fields longitude and latitude or create another model to store location and in User model add ForeignKey .我认为更好的方法是添加两个字段longitudelatitude或创建另一个模型来存储位置并在User模型中添加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 .如果您使用的是 PostgreSQL,则可以使用PostGIS MySQL and Oracle has spacial fields built-in. MySQL和 Oracle 具有内置的空间字段。

Django already supports Geo data. Django 已经支持地理数据。 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.然后您可以进行各种地理查询(例如查找指定区域内的地点,按距离排序等),您的 DBMS 将处理它们。 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 .您可以在Geodjango 文档 中阅读有关它们的更多信息

我推荐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 .正如@p14z 所暗示的那样,保存tuple的最佳方法是ArrayField For my example, I just wanted to save a Polygon extent , with this format:对于我的示例,我只想使用以下格式保存 Polygon extent

(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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM