[PYTHON] Django starting from scratch (part: 2)

Last time

Django starting from zero \ (part: 1 ) -Qiita


Creating your first Django app, part 2|Django documentation| Django

DataBase settings

mysite/setting.py --Python module that describes various settings of jango --Database support etc. are included by default

INSTALLED_APPS Settings for important parts of the application. Details below --django.contrib.admin --Administration (admin) site --django.contrib.auth --Authentication system --django.contrib.contenttypes --Contenttypes framework --django.contrib.sessions --Session framework --django.contrib.messages --Message framework --django.contrib.staticfiles --Static file management framework

Creating a table

Use the following command to create a database table.

python manage.py migrate

-The migrate command refers to the INSTALLED_APPS settings above and creates all the required databases according to the database settings in the` mysite / setting.py' file. --It is possible to display the contents of the table with the command line client. - \dt (PostgreSQL - SHOW TABLES; (MySQL) - .schema (SQLite) - SELECT TABLE_NAME FROM USER_TABLES; (Oracle)

Generate database model

from django.db import models

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

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

--Generating two models, Question and Choice --Both are subclasses of the models class --Each class represents the database feel of the model

--CharFiled, IntegerField, etc. specify what data type to store --Conditions and initial values can be specified, such as models.CharField (max_length = 200) and models.IntegerField (default = 0) --Foreign Key defines a relationship with Question.

Reflect the application in the project

--Add the setting to ʻINSTALLED_APPS in setting.py' to include the application in your project --Set the class described in ʻapps.py in the application (this time Polls) to ʻINSTALLED_APPS


Reflect model changes

Run the code below to save Django's changes in the form of a migration

python manage.py makemigrations polls

 python manage.py check 

Command to check if there is a problem with the project

After creating the model table, execute migrate again to create the model table in the database.

3 steps to implement model changes

--Change model --Run python manage.py make migrations to create migrations --Run python manage.py migrate to apply these changes to the database

Why are the commands for creating and applying migrations separate?

--To commit the migration to the validation management system and distribute it with the app --Easy development ――Because it will be easy to use for other developers and production environments

Improved convenience of database API

If you do >>> Question.objects.all () in the shell The output is as follows. <QuerySet [<Question: Question object (1)>]> I don't know what the database tables look like

So add the `str'method to both Question and Choice

from django.db import models

class Question(models.Model):
    # ...
    def __str__(self):
        return self.question_text

class Choice(models.Model):
    # ...
    def __str__(self):
        return self.choice_text

--In addition to the convenience of displaying in the shell, it is used as an object representation of django's auto-generated admin object. --So it's important to add the __str __ () method to your model


from django.db import models
from django.utils import timezone

class Question(models.Model):
    # ...
    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

Create an admin user

python manage.py createsuperuser

Make it editable on admin

from django.contrib import admin

from .models import Question


Recommended Posts

Django starting from scratch (part: 2)
Django starting from scratch (part: 1)
Django memo # 1 from scratch
Build a bulletin board app from scratch with Django. (Part 2)
Build a bulletin board app from scratch with Django. (Part 3)
Let Code Day75 starting from scratch "15.3 Sum"
Django begins part 1
Django begins part 4
Business efficiency starting from scratch with Python
Let Code Day 29 "46. Permutations" starting from scratch
"Deep Learning from scratch" Self-study memo (Part 12) Deep learning
Let Code Day 27 "101. Symmetric Tree" starting from scratch
Microservices with GCP on RoR starting from scratch
Let Code Day 41 "394. Decode String" starting from scratch
Let Code Day 25 "70. Climbing Stairs" starting from scratch
Let Code Day69 starting from scratch "279. Perfect Squares"
Let Code Day 34 starting from scratch "118. Pascal's Triangle"
Let Code Day85 starting from scratch "6. ZigZag Conversion"
Let Code Day20 starting from scratch "134. Gas Station"
Machine learning starting from scratch (machine learning learned with Kaggle)
Let Code Day 88 "139. Word Break" starting from scratch
Let Code Day 28 "198. House Robber" starting from scratch
Let Code Day 39 "494. Target Sum" starting from scratch
Let Code Day 36 "155. Min Stack" starting from scratch
Let Code Day 17 "169. Majority Element" starting from scratch
Let Code Day 33 "1. Two Sum" starting from scratch
Deep Learning from scratch
Keras starting from nothing
Building Linux From Scratch 10.0
[Python] Django Source Code Reading View Starting from Zero ①
Let Code Day 23 "226. Invert Binary Tree" starting from scratch
Let Code Day8 starting from scratch "1302. Deepest Leaves Sum"
Let Code Day 22 starting from scratch "141. Linked List Cycle"
I set up Django from scratch (Vagrant, Centos, Python3)
Let Code Day 30 starting from scratch "234. Palindrome Linked List"
Let Code Day 32 "437. Path Sum III" starting from scratch
Let Code Day68 starting from scratch "709. To Lower Case"
Deep Learning from scratch 1-3 chapters
Let Code Day 26 starting from scratch "94. Binary Tree Inorder Traversal"
Let Code Day 46 starting from scratch "406. Queue Reconstruction by Height"
ChIP-seq analysis starting from zero
Let Code Day 31 starting from scratch "581. Shortest Unsorted Continuous Subarray"
Deploy Django + React from scratch to GKE (1) Backend development --Nginx + Django
Deploy Django + React from scratch to GKE: Table of Contents
Keras 5th starting from nothing
Use django model from interpreter
Keras starting from nothing 1st
Let Code Day 38 starting from scratch "208. Implement Trie (Prefix Tree)"
Let Code Day3 starting from scratch "1313. Decompress Run-Length Encoded List"
Keras 4th starting from nothing
Template registration from Django Bootstrap
Keras starting from nothing 2nd
I tried to implement Perceptron Part 1 [Deep Learning from scratch]
Keras starting from nothing 3rd
Let Code Day 65 "560. Subarray Sum Equals K" starting from scratch
Let Code Day4 starting from scratch "938. Range Sum of BST"
Deploy Django + React from scratch to GKE (3) Create a GCP project
Lua version Deep Learning from scratch Part 6 [Neural network inference processing]
Re: Life in Heroku starting from scratch with Flask ~ PhantomJS to Heroku ~
Let Code Day 77 starting from scratch "1502. Can Make Arithmetic Progression From Sequence"
Let Code Day 76 starting from scratch "3. Longest Substring Without Repeating Characters"