【问题标题】:How to store long dictionary in Django using postgresql如何使用 postgresql 在 Django 中存储长字典
【发布时间】:2017-07-29 17:19:13
【问题描述】:

我正在尝试使用模型在 Django postgresql 数据库中添加机场代码列表及其名称。我的目标是当有人像您在航空公司网站上看到的那样键入机场代码时,机场名称就会出现。我做了一本这样的字典

    airports = {"JFK": 'New York',
    "AAE": 'Annabah',
    "AAF": 'Apalachicola',
    "AAG": 'Arapoti',
    "AAH": 'Aachen',
    "AAI": 'Arraias',
    "AAJ": 'Awaradam'
    "...": '........'
}

因此,当有人输入 JFK 代码时,会显示纽约机场名称。我知道我必须为此使用 ajax 和 jquery。但首先我必须将数百个机场的字典保存在我的 postgresql 数据库中。任何帮助保存这本字典的最佳方法是什么,我不想一个一个地手动输入它们,因为它们有数百个。

【问题讨论】:

  • 您必须将其作为适当的行存储在您的表中。您正在尝试做的事情需要多个查询,并且一行中的每个字典项都是适合的结构

标签: jquery python ajax django postgresql


【解决方案1】:

你应该使用 JSONField,它允许在你的模型中嵌套字典。

示例

from django.contrib.postgres.fields import JSONField
from django.db import models

class Dog(models.Model):
    name = models.CharField(max_length=200)
    data = JSONField()

    def __str__(self):  # __unicode__ on Python 2
        return self.name

来源:https://docs.djangoproject.com/en/1.10/ref/contrib/postgres/fields/#querying-jsonfield

【讨论】:

    猜你喜欢
    • 2017-08-26
    • 1970-01-01
    • 2013-04-16
    • 2010-09-28
    • 1970-01-01
    • 1970-01-01
    • 2022-07-11
    • 2016-02-21
    • 2012-03-29
    相关资源
    最近更新 更多