简体   繁体   English

将 CSV 文件导入两个独立的 Django 模型

[英]Import CSV file into two separate django models

I'm having trouble parsing data from one csv file into two related tables in a django model.我无法将一个 csv 文件中的数据解析为 django 模型中的两个相关表。

My view.py function.我的 view.py 函数。

        for column in csv.reader(io_string, delimiter=',', quotechar="|"):
            _, created = User.objects.update_or_create(
                card_no=column[0],
                first_name=column[1],
                last_name=column[2],
                mobile=column[3],
                email=column[4],
                is_active=column[5]
            )

            _, created = UserPayment.objects.get_or_create(
                paid_on=column[0],
                valid_until=column[1],
                payment_status=column[2]
            )

This is the CSV file.这是 CSV 文件。 file image文件图像

How can I save the CSV data into the models without any problem?如何将 CSV 数据保存到模型中而不会出现任何问题?

Probably mistake with the column indexes look at the code below列索引可能有误,请看下面的代码

for column in csv.reader(io_string, delimiter=',', quotechar="|"):
    _, created = User.objects.update_or_create(
        card_no=column[0],
        first_name=column[1],
        last_name=column[2],
        mobile=column[3],
        email=column[4],
        is_active=column[5]
    )

    _, created = UserPayment.objects.get_or_create(
        paid_on=column[6], # column[0] is the card_no
        valid_until=column[7], # column[1] is first name
        payment_status=column[8] # column[2] is last name 
    )

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

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