Answer a question

is it possible to do migration from python script?

I am trying to use django on Heliohost where there is no shell but I can use python script.

something like

from django import shell
shell.main(['mysite/manage.py', 'migrate'])

Edit

Using input from @Shadow, I tried putting this code in views.py file

def migrate(request):
    django.setup()
    from django.core.management import call_command
    call_command("migrate", interactive=False)
    return HttpResponse("Final Migration Successful")

Then visited the url mapped to migrate which returned "Final Migration Successful"

then I tried the database like

from .models import Question


class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

Gives me error:

(1146, "Table 'usr_mydb.polls_question' doesn't exist")

From Django Tutorial:

Bypassing manage.py

If you’d rather not use manage.py, no problem. Just set the DJANGO_SETTINGS_MODULE environment variable to mysite.settings, start a plain Python shell, and set up Django:

>>> import django
>>> django.setup()

If this raises an AttributeError, you’re probably using a version of Django that doesn’t match this tutorial version. You’ll want to either switch to the older tutorial or the newer Django version.

You must run python from the same directory manage.py is in, or ensure that directory is on the Python path, so that import mysite works.

For more information on all of this, see the django-admin documentation.

But how to do python manage.py <command> using the django.setup() is nowhere in the documentation.

Answers

You can use call_command to run django manage commands.

Here is an example of using it to call migrate;

from django.core.management import call_command
call_command("migrate", interactive=False)

I have interactive=False because this runs on a continual integration server - but depending on your usage you may wish to omit it.

Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐