0

我正在为 TeamTreehouse.com 的 Python 技术学位的第 4 节做一个项目。我在 2 天内完成了第 4 节,通过了所有测验并完成了所有代码挑战,但在从 CSV 文件读取信息后,我仍然无法找到如何使用 peewee 和 orderedDict 将数据写入 DB 文件。我已经阅读了orderedDict 文档和peewee,但我找不到如何将OrderedDict 写入数据库。

我曾尝试在 teamtreehouse.com 上搜索文档并重新访问培训视频,但根本找不到任何此类示例。

from collections import OrderedDict
import datetime
import sys
import csv

from peewee import *

db = SqliteDatabase('inventory.db')


class Product(Model):
    content = TextField()
    id = PrimaryKeyField()
    product_name = TextField(unique=True)
    product_price = TextField()
    product_quantity = TextField()
    date_updated = DateTimeField(datetime.datetime.now)

    class Meta:
        database = db

def migrate_data():
    with open('inventory.csv') as csvfile:
        reader = csv.reader(csvfile, delimiter=",")
        keys = next(reader)
        #ordered = ([OrderedDict(zip(keys,row)) for row in reader ])
        print('\n\n')
        print([OrderedDict(zip(keys,row)) for row in reader ])
        print('\n\n')



def initialize():
    """ Initialize an Sqlite database called inventory.db."""
    db.connect()
    db.create_tables([Product], safe=True)


def create_model():
    """ Create a model called Product that the Peewee ORM will use to 
build the database. 
The Product model should have five attributes: product_id, product_name, 
product_quantity, 
product_price. Use PeeWee's built in primary_key functionality for the 
product_id field,
 so that each product will have an automatically generated unique 
identifier."""
    productname = ('product_name')

这个问题的预期结果是将通过读取 CSV 文件构建的 OrderedDict 写入使用 peewee 的 sqlite 文件。您可以从我的 github(Yeransian)和“Treehouse-Project4”下下载 CSV 文件和完整的 python 代码

任何能让我摆脱这种低迷的帮助都将是惊人的!我越快恢复学习越好。:)

4

1 回答 1

0

在我看来,一个类似于表格的 csv 应该转换listdicts. 最直接(虽然不是最有效)的方法是遍历这个列表并创建一个Product.

# something along these lines
def save_list_to_db(list_of_dicts_from_csv): 
    for single_product_dict in list_of_dicts_from_csv:
        Product.create(content = single_product_dict['content'],
                       id = single_product_dict['id'], ....
                       )

如前所述,这不是一种非常有效的方法,因为它为每个Product.create(...). 批量插入更有效。您可以在此处阅读相关内容。祝你好运!

于 2019-05-21T01:18:31.653 回答