Is there any way to import models from a server in django?

324 Views Asked by At

There is already a django project existed on a server machine. Now I want to develop another project in another machine using the models of project on the server machine? In brief I want to import the models of a server machine in a project on another machine.

3

There are 3 best solutions below

0
On

Assuming the server you're moving to has no models yet, I would just create the new models.py and migrate, then dump the relevant tables from the old environment, and move them to the new one.

If there are already models on the new environment, you could do the old hack of incrementing the pks by 100 (or 1000 or whatever), then dump and import.

Though may be better to import them through Django.

Or if you really want to get kludgy:

for s in SomeModel.objects.all():
    print "n = NewModel(property1='"+s.property1+"', property2='"+s.property2+"')"
    print "n.save()"

Take the output of that, and run it on the new server. Add more for related models, etc.

0
On

The best way to import/export data throught Django is to use django-admin dumpdata and loaddata commands: https://docs.djangoproject.com/en/1.8/ref/django-admin/

manage.py dumpdata --all --format json >> mydata.json
manage.py loaddata mydata.json
0
On

If you're speaking of the models themselves (not the data) :

  • If you have access to the files, just copy the model, it is by far the easiest way to do it.

  • But if you don't, but have access to the database, you can do : $ python manage.py inspectdb > models.py after having set the db settings. This generated file will contain the models definitions.

I have never had to try it, but I guess if the source db was generated using Django, and without too many custom fields types, it should give you good results.

Then you'll be able to base your real databse upon what has been generated (using your own database settings and the models file generated).

More info here

If you also need the data, a simple dump of the database should help you a lot, then you'd have to import it in your generated database.