[Django]-Accssesing table with django shell

3👍

If your table in database is named main_A then in Django models.py you should define the class as A not main_A:

from django.db import  models
class A(models.Model):
       x= models.IntegerField(primary_key = True)
       y= models.IntegerField(blank = True)

then in Shell:

from main.models import A
p1 = A.objects.all()
p1
👤John

2👍

There are some keynotes that must be kept in mind, when designing models. Name of table is automatically derived from model metadata.

Django will define the name of tables as appname_tablename, if not defined explicitly.

For example : Let’s my project name is Education, app name is University. I have created a table named student as follows :

class Student (models.Model):
    name = models.CharField(max_length = 30)
    section = models.CharField(max_length = 1)

Django will define it in database as follows :

CREATE TABLE university_student (
"id" serial NOT NULL PRIMARY KEY,
"name" varchar(30) NOT NULL,
"section" varchar(1) NOT NULL );

(Note : An id field is added automatically, you can change this behaviour too)

Now, to give the name of your tables the way you like and not the way Django defines them, you need to use an inner class Meta like :

class Student (models.Model):
    name = models.CharField(max_length = 30)
    section = models.CharField(max_length = 1)
    class Meta:
        db_table = 'Student'

1👍

Like PyDroid said,
You need to run 2 commands, go to shell, then import your table into shell, then query your data

python manage.py makemigrations
python manage.py migrate
python manage.py shell
from apps.yourappname import *
Main_A.objects.all().values()

0👍

In Django, you create project and then multiple apps. Each app has its own model. I don’t know what is your project structure (project + apps), but I assume that you have your models package present in a separate app. So, whenever you want to access any model, you need to qualify it with the package name. Example, if you have an app say “mysite” with a model say “User”, then you have to access user model as

from mysite.models import User

then you can use User model.

There might be many apps in a project with its own models, so qualifying “models” with the name of app is must, otherwise Django framework will be confused as to which app’s models it should import from.

-2👍

when u created the model in models.py than u need 2 command
    first.
    python manage.py makemigrations
    second.
    python manage.py migrate

    after you get the results empty
    >>> p1 = main_A.objects.all()
    >>> p1
    []
👤Droid

Leave a comment