List Django database table names from external script












0















I am trying to access sqlite3 database that I have in my Django project from within external script that is not part of the project.



However, the following will return an empty list:



con = sqlite3.connect('database.db')
cursor = con.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
print(cursor.fetchall())


Even though I have already saved some models to the database.
To check the table names, I use the following in Django shell:



>>> tables = connection.introspection.table_names()
>>> seen_models = connection.introspection.installed_models(tables)
>>> seen_models
{<class 'django.contrib.auth.models.Permission'>, <class 'django.contrib.sessions.models.Session'>, <class 'django.contrib.contenttypes.models.ContentType'>, <class 'explorer_api.models.Athlete'>, <class 'django.contrib.admin.models.LogEntry'>, <class 'django.contrib.auth.models.Group'>, <class 'explorer_api.models.Activity'>, <class 'django.contrib.auth.models.User'>}
>>> tables
['auth_group', 'auth_group_permissions', 'auth_permission', 'auth_user', 'auth_user_groups', 'auth_user_user_permissions', 'django_admin_log', 'django_content_type', 'django_migrations', 'django_session', 'explorer_api_activity', 'explorer_api_athlete']


I have not specified the table names explicitly in model's Meta, so I guess the table names are appname_modelname (explorer_api_activity and explorer_api_athlete).



But why the empty list?










share|improve this question


















  • 2





    have you used the correct name of the database?

    – ruddra
    Nov 24 '18 at 7:13











  • You're right, the above scripts work only when it is in the same folder as the database. What if I want it to be elsewhere? In such case I am currently referencing the database location like this:'/media/barciewicz/DATA/python_projects/strava/explorer_api/db.sqlite3', but this is when empty list is returned.

    – barciewicz
    Nov 27 '18 at 18:18













  • Yes its possible. Please see my answer on this. thanks.

    – ruddra
    Nov 28 '18 at 1:31
















0















I am trying to access sqlite3 database that I have in my Django project from within external script that is not part of the project.



However, the following will return an empty list:



con = sqlite3.connect('database.db')
cursor = con.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
print(cursor.fetchall())


Even though I have already saved some models to the database.
To check the table names, I use the following in Django shell:



>>> tables = connection.introspection.table_names()
>>> seen_models = connection.introspection.installed_models(tables)
>>> seen_models
{<class 'django.contrib.auth.models.Permission'>, <class 'django.contrib.sessions.models.Session'>, <class 'django.contrib.contenttypes.models.ContentType'>, <class 'explorer_api.models.Athlete'>, <class 'django.contrib.admin.models.LogEntry'>, <class 'django.contrib.auth.models.Group'>, <class 'explorer_api.models.Activity'>, <class 'django.contrib.auth.models.User'>}
>>> tables
['auth_group', 'auth_group_permissions', 'auth_permission', 'auth_user', 'auth_user_groups', 'auth_user_user_permissions', 'django_admin_log', 'django_content_type', 'django_migrations', 'django_session', 'explorer_api_activity', 'explorer_api_athlete']


I have not specified the table names explicitly in model's Meta, so I guess the table names are appname_modelname (explorer_api_activity and explorer_api_athlete).



But why the empty list?










share|improve this question


















  • 2





    have you used the correct name of the database?

    – ruddra
    Nov 24 '18 at 7:13











  • You're right, the above scripts work only when it is in the same folder as the database. What if I want it to be elsewhere? In such case I am currently referencing the database location like this:'/media/barciewicz/DATA/python_projects/strava/explorer_api/db.sqlite3', but this is when empty list is returned.

    – barciewicz
    Nov 27 '18 at 18:18













  • Yes its possible. Please see my answer on this. thanks.

    – ruddra
    Nov 28 '18 at 1:31














0












0








0


0






I am trying to access sqlite3 database that I have in my Django project from within external script that is not part of the project.



However, the following will return an empty list:



con = sqlite3.connect('database.db')
cursor = con.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
print(cursor.fetchall())


Even though I have already saved some models to the database.
To check the table names, I use the following in Django shell:



>>> tables = connection.introspection.table_names()
>>> seen_models = connection.introspection.installed_models(tables)
>>> seen_models
{<class 'django.contrib.auth.models.Permission'>, <class 'django.contrib.sessions.models.Session'>, <class 'django.contrib.contenttypes.models.ContentType'>, <class 'explorer_api.models.Athlete'>, <class 'django.contrib.admin.models.LogEntry'>, <class 'django.contrib.auth.models.Group'>, <class 'explorer_api.models.Activity'>, <class 'django.contrib.auth.models.User'>}
>>> tables
['auth_group', 'auth_group_permissions', 'auth_permission', 'auth_user', 'auth_user_groups', 'auth_user_user_permissions', 'django_admin_log', 'django_content_type', 'django_migrations', 'django_session', 'explorer_api_activity', 'explorer_api_athlete']


I have not specified the table names explicitly in model's Meta, so I guess the table names are appname_modelname (explorer_api_activity and explorer_api_athlete).



But why the empty list?










share|improve this question














I am trying to access sqlite3 database that I have in my Django project from within external script that is not part of the project.



However, the following will return an empty list:



con = sqlite3.connect('database.db')
cursor = con.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
print(cursor.fetchall())


Even though I have already saved some models to the database.
To check the table names, I use the following in Django shell:



>>> tables = connection.introspection.table_names()
>>> seen_models = connection.introspection.installed_models(tables)
>>> seen_models
{<class 'django.contrib.auth.models.Permission'>, <class 'django.contrib.sessions.models.Session'>, <class 'django.contrib.contenttypes.models.ContentType'>, <class 'explorer_api.models.Athlete'>, <class 'django.contrib.admin.models.LogEntry'>, <class 'django.contrib.auth.models.Group'>, <class 'explorer_api.models.Activity'>, <class 'django.contrib.auth.models.User'>}
>>> tables
['auth_group', 'auth_group_permissions', 'auth_permission', 'auth_user', 'auth_user_groups', 'auth_user_user_permissions', 'django_admin_log', 'django_content_type', 'django_migrations', 'django_session', 'explorer_api_activity', 'explorer_api_athlete']


I have not specified the table names explicitly in model's Meta, so I guess the table names are appname_modelname (explorer_api_activity and explorer_api_athlete).



But why the empty list?







python django sqlite3






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 24 '18 at 6:41









barciewiczbarciewicz

672313




672313








  • 2





    have you used the correct name of the database?

    – ruddra
    Nov 24 '18 at 7:13











  • You're right, the above scripts work only when it is in the same folder as the database. What if I want it to be elsewhere? In such case I am currently referencing the database location like this:'/media/barciewicz/DATA/python_projects/strava/explorer_api/db.sqlite3', but this is when empty list is returned.

    – barciewicz
    Nov 27 '18 at 18:18













  • Yes its possible. Please see my answer on this. thanks.

    – ruddra
    Nov 28 '18 at 1:31














  • 2





    have you used the correct name of the database?

    – ruddra
    Nov 24 '18 at 7:13











  • You're right, the above scripts work only when it is in the same folder as the database. What if I want it to be elsewhere? In such case I am currently referencing the database location like this:'/media/barciewicz/DATA/python_projects/strava/explorer_api/db.sqlite3', but this is when empty list is returned.

    – barciewicz
    Nov 27 '18 at 18:18













  • Yes its possible. Please see my answer on this. thanks.

    – ruddra
    Nov 28 '18 at 1:31








2




2





have you used the correct name of the database?

– ruddra
Nov 24 '18 at 7:13





have you used the correct name of the database?

– ruddra
Nov 24 '18 at 7:13













You're right, the above scripts work only when it is in the same folder as the database. What if I want it to be elsewhere? In such case I am currently referencing the database location like this:'/media/barciewicz/DATA/python_projects/strava/explorer_api/db.sqlite3', but this is when empty list is returned.

– barciewicz
Nov 27 '18 at 18:18







You're right, the above scripts work only when it is in the same folder as the database. What if I want it to be elsewhere? In such case I am currently referencing the database location like this:'/media/barciewicz/DATA/python_projects/strava/explorer_api/db.sqlite3', but this is when empty list is returned.

– barciewicz
Nov 27 '18 at 18:18















Yes its possible. Please see my answer on this. thanks.

– ruddra
Nov 28 '18 at 1:31





Yes its possible. Please see my answer on this. thanks.

– ruddra
Nov 28 '18 at 1:31












1 Answer
1






active

oldest

votes


















0














From comments on on the question:
Yes its possible to run this script as long as you have a valid path to the file. I have rewritten your script with minor changes like this:



import sqlite3
import os.path

try:
file_name = raw_input("Enter File Path? ")
except:
file_name = input("Enter File Path? ")
if os.path.isfile(file_name):
con = sqlite3.connect(file_name)
cursor = con.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
print(cursor.fetchall())
else:
print("File does not exist")


Usage:



> python sqlite_tables.py
(prompt)> Enter File Path? random/file/path
(prompt)> File does not exist

> python sqlite_tables.py
(prompt)> Enter File Path? /valid/path/to/database.db
(prompt)> [(u'django_migrations',), (u'sqlite_sequence',)...]

> python sqlite_tables.py
(prompt)> Enter File Path? ../database.db # relative path
(prompt)> [(u'django_migrations',), (u'sqlite_sequence',)...]





share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53455827%2flist-django-database-table-names-from-external-script%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    From comments on on the question:
    Yes its possible to run this script as long as you have a valid path to the file. I have rewritten your script with minor changes like this:



    import sqlite3
    import os.path

    try:
    file_name = raw_input("Enter File Path? ")
    except:
    file_name = input("Enter File Path? ")
    if os.path.isfile(file_name):
    con = sqlite3.connect(file_name)
    cursor = con.cursor()
    cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
    print(cursor.fetchall())
    else:
    print("File does not exist")


    Usage:



    > python sqlite_tables.py
    (prompt)> Enter File Path? random/file/path
    (prompt)> File does not exist

    > python sqlite_tables.py
    (prompt)> Enter File Path? /valid/path/to/database.db
    (prompt)> [(u'django_migrations',), (u'sqlite_sequence',)...]

    > python sqlite_tables.py
    (prompt)> Enter File Path? ../database.db # relative path
    (prompt)> [(u'django_migrations',), (u'sqlite_sequence',)...]





    share|improve this answer






























      0














      From comments on on the question:
      Yes its possible to run this script as long as you have a valid path to the file. I have rewritten your script with minor changes like this:



      import sqlite3
      import os.path

      try:
      file_name = raw_input("Enter File Path? ")
      except:
      file_name = input("Enter File Path? ")
      if os.path.isfile(file_name):
      con = sqlite3.connect(file_name)
      cursor = con.cursor()
      cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
      print(cursor.fetchall())
      else:
      print("File does not exist")


      Usage:



      > python sqlite_tables.py
      (prompt)> Enter File Path? random/file/path
      (prompt)> File does not exist

      > python sqlite_tables.py
      (prompt)> Enter File Path? /valid/path/to/database.db
      (prompt)> [(u'django_migrations',), (u'sqlite_sequence',)...]

      > python sqlite_tables.py
      (prompt)> Enter File Path? ../database.db # relative path
      (prompt)> [(u'django_migrations',), (u'sqlite_sequence',)...]





      share|improve this answer




























        0












        0








        0







        From comments on on the question:
        Yes its possible to run this script as long as you have a valid path to the file. I have rewritten your script with minor changes like this:



        import sqlite3
        import os.path

        try:
        file_name = raw_input("Enter File Path? ")
        except:
        file_name = input("Enter File Path? ")
        if os.path.isfile(file_name):
        con = sqlite3.connect(file_name)
        cursor = con.cursor()
        cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
        print(cursor.fetchall())
        else:
        print("File does not exist")


        Usage:



        > python sqlite_tables.py
        (prompt)> Enter File Path? random/file/path
        (prompt)> File does not exist

        > python sqlite_tables.py
        (prompt)> Enter File Path? /valid/path/to/database.db
        (prompt)> [(u'django_migrations',), (u'sqlite_sequence',)...]

        > python sqlite_tables.py
        (prompt)> Enter File Path? ../database.db # relative path
        (prompt)> [(u'django_migrations',), (u'sqlite_sequence',)...]





        share|improve this answer















        From comments on on the question:
        Yes its possible to run this script as long as you have a valid path to the file. I have rewritten your script with minor changes like this:



        import sqlite3
        import os.path

        try:
        file_name = raw_input("Enter File Path? ")
        except:
        file_name = input("Enter File Path? ")
        if os.path.isfile(file_name):
        con = sqlite3.connect(file_name)
        cursor = con.cursor()
        cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
        print(cursor.fetchall())
        else:
        print("File does not exist")


        Usage:



        > python sqlite_tables.py
        (prompt)> Enter File Path? random/file/path
        (prompt)> File does not exist

        > python sqlite_tables.py
        (prompt)> Enter File Path? /valid/path/to/database.db
        (prompt)> [(u'django_migrations',), (u'sqlite_sequence',)...]

        > python sqlite_tables.py
        (prompt)> Enter File Path? ../database.db # relative path
        (prompt)> [(u'django_migrations',), (u'sqlite_sequence',)...]






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 28 '18 at 1:31

























        answered Nov 24 '18 at 7:11









        ruddraruddra

        14.9k32748




        14.9k32748
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53455827%2flist-django-database-table-names-from-external-script%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Create new schema in PostgreSQL using DBeaver

            Deepest pit of an array with Javascript: test on Codility

            Costa Masnaga