简体   繁体   English

如何在创建 Django model 时填充表?

[英]How to populate a table while creating the Django model?

I have a list of cities (simple cvs file) and I want to populate the citeis table while creating the City model.我有一个城市列表(简单的 cvs 文件),我想在创建城市 model 时填充 citeis 表。 Class description: Class 说明:

class City(models.Model):
    city = modeld.CharField('city_name', max_length=50)

    class Meta:
        berbuse_name =....
        ...........

    def __unicode__(self):
        return self.city

Now, what I am looking for is how to do it only once, while creating the model(DB table).现在,我正在寻找的是如何只做一次,同时创建模型(数据库表)。

I'm trying to do it over here because it sound very logic to me (like building a sql script in MS-sql and other)我想在这里做,因为这对我来说听起来很合乎逻辑(比如在 MS-sql 和其他中构建 sql 脚本)

EDIT: Ok, I guess I am asking the wrong thing....maybe this: How do I create a python function that will take the cvs file and transform it to json (Again, in the model itself, while it is being build) and should I do it at all??? EDIT: Ok, I guess I am asking the wrong thing....maybe this: How do I create a python function that will take the cvs file and transform it to json (Again, in the model itself, while it is being build ) 我应该这样做吗???

Can any one please help me with this?有人可以帮我吗?

We do something like this, usually.我们通常会这样做。

import csv
from my_django_app.forms import CityForm
with open( "my file", "rb" ) as source:
    rdr = csv.DictReader( source )
    for row in rdr:
        form= CityForm( **row )
        if form.is_valid(): 
            form.save()
        else:
            print form.errors

This validates and loads the data.这将验证并加载数据。

After the data is loaded, you can use django-admin dumpdata to preserve a JSON fixture from the loaded model.加载数据后,您可以使用django-admin dumpdata数据从加载的 model 中保留 JSON 夹具。

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

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