how do I run a django script from command line or Pycharm?

698 views
Skip to first unread message

frocco

unread,
Mar 12, 2013, 8:42:22 PM3/12/13
to django...@googlegroups.com
I want to run the code below in a file called migration.py

from django.db import connections
from django.core.exceptions import ObjectDoesNotExist
from django.db.utils import ConnectionDoesNotExist
from django.conf import settings
import models


def setup_cursor():
    try:
        cursor = connections['legacy'].cursor()
    except ConnectionDoesNotExist:
        print "Legacy database is not configured"
        return None


def import_products():
    cursor = setup_cursor()
    if cursor is None:
        return
        ## it's important selecting the id field, so that we can keep the publisher - book relationship
    sql = """SELECT * FROM shopinventory"""
    cursor.execute(sql)
    for row in cursor.fetchall():
        p = models.Product.objects.get(sku=row['Item'])
        if p:
            p.meta_keywords = row['Item_description']
            p.save()


def main():
    import_products()


if __name__=="__main__":
    main()

Andy McKay

unread,
Mar 13, 2013, 12:39:35 AM3/13/13
to django...@googlegroups.com
On Tue, Mar 12, 2013 at 5:42 PM, frocco <far...@gmail.com> wrote:
> I want to run the code below in a file called migration.py

django-extensions will do this for you, if you create a run method.

http://blog.brendel.com/2012/01/how-to-use-djangextensions-runscript.html

Tom Evans

unread,
Mar 13, 2013, 5:54:34 AM3/13/13
to django...@googlegroups.com
On Wed, Mar 13, 2013 at 12:42 AM, frocco <far...@gmail.com> wrote:
> I want to run the code below in a file called migration.py
>

3 options:

1) Setup the django environment manually in your scripts:

https://docs.djangoproject.com/en/1.5/topics/settings/#either-configure-or-django-settings-module-is-required

2) Write a management command

https://docs.djangoproject.com/en/1.5/howto/custom-management-commands/

3) Use an extension like django-extensions as mentioned by Andy

Cheers

Tom

frocco

unread,
Mar 13, 2013, 6:11:28 AM3/13/13
to django...@googlegroups.com
Thank you, I am going to try the extensions first.

Regards,

Frank

Reply all
Reply to author
Forward
0 new messages