0

I have a problem of creating a big amount of data with foreign keys in Django ORM on MySql. Let's say I have 2 models:

class Student(models.Model):
    school = models.ForeignKey(School, related_name="students")
    name = models.CharField(max_length=200, blank=True, default="")

class School(models.Model):
    name = models.CharField(max_length=200, blank=True, default="")

Now I want to create a lot of schools that have a lot of students, and lets assume I already have a Data structure that have all the needed info for the creation of it.

The only way I found out so far is to create all the schools (in order to get the PK) and on the go to create a list of all the students(in all of the schools) and use bulk_create to create the students.

It seems that there should be a better way to do this.

Because if for example we have 10K schools and 200 students in school the lowest I managed to do is ~10K inserts and that is to much.

Thank you in advance.

Val.K
  • 91
  • 1
  • 10
  • Possible duplicate of [Django insert default data after migrations](http://stackoverflow.com/questions/39739439/django-insert-default-data-after-migrations) – Sardorbek Imomaliev Oct 26 '16 at 09:20
  • I am maybe missing something, but this is more for a one-time solution rather then something you put in your program. – Val.K Oct 26 '16 at 10:35
  • Can you post a sample of your current data structure you use for bulk create? And probably some of the code you already tried? – Todor Oct 26 '16 at 10:58

1 Answers1

0

I think you are doing it incorrectly. It is better to use fixtures for this

Read more https://docs.djangoproject.com/en/1.10/howto/initial-data/ and https://code.djangoproject.com/wiki/Fixtures

Basically you will create file that will store current data of your db and then run command ./manage.py loaddata that will handle upload in most optimal way

Sardorbek Imomaliev
  • 14,861
  • 2
  • 51
  • 63
  • Maybe I gave a bad example but I need to this as part of my code multiple times and not once or during development only. I said that we already have the data not as hard coded or anything like that... I just created the and store it in a data structure. – Val.K Oct 26 '16 at 10:29
  • @Val.K what do you mean by "multiple times"? You can `./manage.py loaddata` mulitiple times. – Sardorbek Imomaliev Oct 26 '16 at 10:31
  • By multiple times i mean use it as part of my code.. for example I have a user that uses my software and as part of the everyday use (lots of times a day) he needed to do what i described. in order for it to be more real lets say I have 1K of schools and 10 students per school – Val.K Oct 26 '16 at 10:47
  • @Val.K if your data is predefined what is the problem of executing this command in your view? And I still don't get why would anyone want to create same data over and over. – Sardorbek Imomaliev Oct 26 '16 at 10:50