簡體   English   中英

如何在 Django 數據庫模型的字段中存儲字典?

[英]How to store a dictionary in a Django database model's field?

我想將此字典列表存儲在 Django 數據庫中:

h =  [

{'sale_id': 14,
  'name': 'Macarena',
  'fecha': datetime.date(2021, 3, 11),
  'debe': 500.0},
 {'sale_id': 14,
  'name': 'Macarena',
  'fecha': datetime.date(2021, 4, 11),
  'debe': 500.0},
 {'sale_id': 15,
  'name': 'Yamila',
  'fecha': datetime.date(2021, 4, 14),
  'debe': 2000.0}

] 

我試過這個:

h = tabla_creditos()

class Creditos1(models.Model):

    sale_id = models.IntegerField(default=0)
    name = models.CharField(max_length=150)
    fecha = models.DateTimeField(default=datetime.now)
    debe = models.IntegerField(default=0)

for i in range(0,len(h)):
    Creditos1.objects.create(name=h[i]['name'], sale_id=h[i]['sale_id'], fecha=h[i]['fecha'], debe=h[i]['debe'])

其中“h”是那個字典,它是由“tabla_creditos()”函數產生的。 然后,我嘗試使用“objects.create”為數據庫創建值,但我在數據庫中存儲了重復的值:

在此處輸入圖片說明

那么,如何將該 dict 存儲在數據庫中?

我找到了這個解決方案: How to store a dictionary in a Django database model's field但沒有一個答案對我有幫助。

謝謝!

編輯通過 Rohith 的回答,我得到了這個:

在此處輸入圖片說明

但我想要這樣的東西,在 DB 列中轉換 dict 的每個鍵:

在此處輸入圖片說明

有幾種方法可以在模型中保存字典。 我提到了 JSON 字段的使用。

如果您使用 PostgreSql 作為您的數據庫,那么您可以訪問JSON Field 你可以在文檔中閱讀它。 這將讓您將字典保存為 Django 支持的 JSON 文件

例如:

from django.contrib.postgres.fields import JSONField

class Creditos1(models.Model):
    dict_info = JSONField(default=dict)

在您的代碼中

sample_dict =  [

{'sale_id': 14,
  'name': 'Macarena',
  'fecha': datetime.date(2021, 3, 11),
  'debe': 500.0},
 {'sale_id': 14,
  'name': 'Macarena',
  'fecha': datetime.date(2021, 4, 11),
  'debe': 500.0},
 {'sale_id': 15,
  'name': 'Yamila',
  'fecha': datetime.date(2021, 4, 14),
  'debe': 2000.0}

]

credit = Creditos1.objects.create(dict_info=sample_dict)

如果您使用任何其他數據庫,我建議將字段創建為CharField() 然后將 dict 編碼為 JSON 字符串並將該字符串保存到 Credit 中。 然后您可以解碼 JSON 字符串。

例如:

class Creditos1(models.Model):
    dict_info = CharField(blank=True, null=True)

在您的代碼中:

import json
sample_dict =  [
    
    {'sale_id': 14,
      'name': 'Macarena',
      'fecha': datetime.date(2021, 3, 11),
      'debe': 500.0},
     {'sale_id': 14,
      'name': 'Macarena',
      'fecha': datetime.date(2021, 4, 11),
      'debe': 500.0},
     {'sale_id': 15,
      'name': 'Yamila',
      'fecha': datetime.date(2021, 4, 14),
      'debe': 2000.0}
    
    ]
    encoded_json = json.dumps(sample_dict)
    credit = Creditos1.objects.create(dict_info=encoded_json)

為了獲取字典的值,您可以使用json.loads()

decoded_data = json.loads(credit.dict_info)
print(decoded_data[0]["name"])

更新

根據我的理解,函數tabla_creditos()仍然不清楚,這可能是創建多個對象的原因,甚至可能是您沒有清除數據庫(使用代碼刪除所有記錄Creditos1.objects.all ().刪除() )。

如果要將字典列表另存為每個對象,(假設您有一個干凈的數據庫)您的代碼:

h = some_func()
uniquefied_list = list({v['sale_id']:v for v in h}.values())
for x in range(0, len(uniquefied_list)):
    Creditos1.objects.get_or_create(name=h[x]["name"], debe=h[x]["debe"]....)

在這里, get_or_create 將是處理此問題的更好方法 這是文檔

希望這能解決您的問題。

使用 JSON 字段。 請注意,它在 SQLite 中不受支持

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM