各位大神好,我剛接觸 Django 沒多久,有個小專案要做 API 的處理。如標題的問題困擾我一陣子,也試了很多方法,但都無法解決。我的想法是先建立 model ,再將 JSON 檔案 migrate 到資料庫中,但 JSON 檔案都無法匯入到資料庫。
有錯的地方、或是觀念,請各位不吝指點謝謝!!
下方為 JSON 檔案格式
依照 JSON 的資料型態建立的 model
from django.db import models
WEEKDAYS = [
(1, ("Monday")),
(2, ("Tuesday")),
(3, ("Wednesday")),
(4, ("Thursday")),
(5, ("Friday")),
(6, ("Saturday")),
(7, ("Sunday")),
]
class BookStore(models.Model):
cash_balance = models.FloatField(null=False)
store_name = models.CharField(max_length=100, null=False)
class Book(models.Model):
books_store = models.ForeignKey(BookStore, on_delete=models.CASCADE)
book_name = models.CharField(max_length=100, null=False)
price = models.FloatField(null=False)
class OpeningHour(models.Model):
books_store = models.ForeignKey(BookStore, on_delete=models.CASCADE)
week_day = models.CharField(max_length=20, choices=WEEKDAYS)
start_min = models.TimeField()
end_min = models.TimeField()
要將 JSON 資料存入資料庫,寫了一個 0002migration.py
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('bookstore_api', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='OpeningHour',
fields=[
('id', models.BigAutoField(auto_created=True,
primary_key=True, serialize=False, verbose_name='ID')),
('week_day', models.CharField(choices=[(1, 'Monday'), (2, 'Tuesday'), (3, 'Wednesday'), (
4, 'Thursday'), (5, 'Friday'), (6, 'Saturday'), (7, 'Sunday')], max_length=20)),
('start_min', models.TimeField()),
('end_min', models.TimeField()),
],
),
migrations.RenameField(
model_name='book',
old_name='books',
new_name='books_store',
),
migrations.RemoveField(
model_name='bookstore',
name='opening_hours',
),
migrations.DeleteModel(
name='OpeningHours',
),
migrations.AddField(
model_name='openinghour',
name='books_store',
field=models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE, to='bookstore_api.bookstore'),
),
]
最後執行了python3 manage.py migrate JSON檔案
出現這個問題,也找了相關問題,都還是卡在這部份。
django.core.serializers.base.DeserializationError: Problem installing fixture
你是想要將JSON的檔案轉入到關係型資料庫嗎??
如果是的話,你可以利用Django自身的交互工具配合pandas來匯入JSON檔案
# 最好安裝一下ipython
pip install ipython
# project中執行下面的指令進入 交互模式
python manage.py shell
匯入數據的範例
import pandas as pd
# json檔案的路徑
data = pd.read_json('/Users/yusing/Desktop/BigTeaRich/singflow/base_data/province-city-china/data.json')
# 將讀取到到資料轉變成python 中到字典
data = data.to_dict('records')
# 對資料進行一定處理,視情況而定
provice = list(filter(lambda x:x['city'] ==0 ,data))
# 逐一寫入資料
for each in provice:
# 寫入的模型
p = Province()
p.title = each['name']
p.code = str(each['code'])
print(str(each['code']))
print(p)
p.save()