Re: Bulk import of data
On Fri, Nov 25, 2011 at 2:03 PM, Fabio Natali <fabio@fnstudio.it> wrote:
> Hi everybody!
>
> I have a CSV file and have to import it in my Django website.
>
> Say I have three models involved: category, sub_category and product.
>
> ### models.py ###
> class Category(models.Model):
> name = models.CharField(max_lenth=100)
>
> class SubCategory(models.Model):
> name = models.CharField(max_length=100)
> parent_category = models.ForeignKey(Category)
>
> class Product(models.Model):
> name = models.CharField(max_length=200)
> sub_category = models.ForeignKey(SubCategory)
> ##########
>
>
> Say this is my CSV file (category, sub_category, product):
>
> ### file.csv ###
> clothing man;trousers;levis 501
> clothing woman;shirt;nice shirt
> [...]
> ##########
>
>
> I am not sure on which way to go. Do you have any hints or web references to
> look at?
>
It's not that tricky, is it?
Read the CSV file, split out the fields.
Get or create the category
Get or create the subcategory
Get or create the product
in code:
import csv
data = csv.reader(open('/path/to/csv', 'r'), delimiter=';')
for row in data:
category = Category.objects.get_or_create(name=row[0])
sub_category = SubCategory.objects.get_or_create(name=row[1],
defaults={'parent_category': category})
product = Product.objects.get_or_create(name=row[2],
defaults={'sub_category': sub_category})
http://docs.python.org/library/csv.html
Cheers
Tom
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home