Contents: CSV importer is a tool which allow you to transform easily a csv file into a python object or a django model instance. It is based on a django-style declarative model.
Simple, like Pypi package:
or with Pip
pip install csvImporter
Here is a basic sample:
>>> class MyCSvModel(CsvModel): >>> name = CharField() >>> age = IntegerField() >>> length = FloatField() >>> >>> class Meta: >>> delimiter = ";"
You declare a MyCsvModel which will match to a csv file like this: “Anthony;27;1.75”
To import the file or any iterable object, just do:
>>> my_csv_list = MyCsvModel.import_data(data = open("my_csv_file_name.csv")) >>> first_line = my_csv_list >>> first_line.age 27
Without an explicit declaration, data and columns are matched in the same order:
If you now want to interact with a django model, you just have to add a dbModel option to the class meta.
>>> from model import CsvModel >>> >>> class MyCSvModel(CsvModel): >>> name = CharField() >>> age = IntegerField() >>> length = FloatField() >>> >>> class Meta: >>> delimiter = ";" >>> dbModel = Person
That will automatically match to the following django model.
>>> class Person(models.Model): >>> name = CharField(max_length = 100) >>> age = IntegerField() >>> length = FloatField()
If field names of your Csv model does not match the field names of your django model, you can manage this with the match keyword:
>>> class MyCSvModel(CsvModel): >>> fullname = CharField(match = "name") ...
If you don’t want to have to re-declare a CSV model whereas the Django model already exist, use a CsvDbModel.
>>> from my_projects.models import Person >>> from csvImporter.model import CsvDbModel >>> >>> class MyCsvModel(CsvDbModel): >>> >>> class Meta: >>> dbModel = Person >>> delimiter = ";"
The django model should be imported in the model
Fields available are:
You can give, as argument, the following options:
Here is an example of a way to use the transform attribute.
>>> class MyCsvModel(CsvModel): >>> >>> user = ForeignKey(transform = lambda user: user.username)
ForeignKey has an additional argument:
You can also skip a row during prepare, transform or in a validator by raising a SkipRow exception.
Set it to LinearLayout ( by default ) or Tabular Layout. Modify the way your data are organised in.22 the file. Tabular read:
B1 B2 B3
A1 C1 C2 C3 A2 C4 C5 C6 –> (A1,B1,C1), (A1,B2,C2), (A1,B3,C3), (A2,B1,C4) ... A3 C7 C8 C9
When importing data, you can add an optional argument extra_fields which is a string or a list. This allow to add a value to any line of the csv file before the loading.
If you want to create more than object by line, you should use a group CSV model. This object will create the object in the same order than the csv_models attribute provided.