iscott
4/23/2020 - 7:55 AM

Python/Django command lines

Run Server:

python3 manage.py runserver

Create DB:

createdb

Make migrations:

python3 manage.py makemigrations

Migrate DB:

python3 manage.py migrate

Show Migrations:

python manage.py showmigrations

Create a project:

django-admin startproject

Create an app:

python3 manage.py startapp main_app

Create an admin user for the Django Admin site:

python3 manage.py createsuperuser

Run Django Shell:

python3 manage.py shell

Import models in shell:

from <app_name>.models import *

Shell commands:

c = Cat.objects.get(id=3) # return one
Cat.objects.filter(id=3) # return QuerySet
Question.objects.filter(question_text__startswith='What')
Cat.objects.all()
Cat.objects.first()

Create a record:

q = Question(question_text="What's new?", pub_date=timezone.now())
q.save()

To access through a has_many relationship, append _set. Example:

# display all Choices (from Choice model) related to Question
Question.objects.last().choice_set.all()
# How many questions are in the questions table?
Question.objects.all().count()

delete a record:

c.delete()