Образовательный проект «SnakeProject» Михаила Козлова

Навигация

⇒ Python ⇐

CISCO

Voice(Asterisk\Cisco)

Microsoft

Powershell

SQL\T-SQL

FreeBSD and Nix

Общая

WEB Разработка

ORACLE SQL \ JAVA

Мото

Стрельба, пневматика, оружие

Саморазвитие и психология


Django: простой проект часть 3


Продолжаем серию статей по "Django: простой проект":

Предыдущие статьи:

Django: простой проект

Django: простой проект часть 2

 

В этой статье мы научимся вносить изменения в базу данных на примере добавления поля "boss"


Изменяем модель(например добавим поле "boss"):

C:\django_code\first\firstapp\models.py

 

Команда makemigrations - cоздает новые миграции на основе изменений, обнаруженных в вашей модели.

C:\django_code\first>C:\Python33\python.exe C:\django_code\first\manage.py makemigrations

 

Команда syncdb анализирует значение INSTALLED_APPS и создает все необходимые таблицы в базе данных используя настройки базы данных из файла settings.py.

C:\django_code\first>C:\Python33\python.exe C:\django_code\first\manage.py syncdb

 

Возникла проблема с dbshell: "sqlite3" не является внутренней или внешней командой, исполняемой программой или пакетным файлом
качаем sqlite-shell-win32-x86-3080701.zip с http://sqlite.org/download.html    
распаковываем "экзешник" из архива например в "C\Python33\", 
обязательно убедитесь, чтоб этот путь был в переменной PATH в свойствах моего компьютера-доп.параметры системы-переменные среды

 

Теперь запускаем dbshell

c:\django_code>C:\Python33\python.exe C:\django_code\first\manage.py dbshell

 

Помощь по командам

sqlite> .help
.backup ?DB? FILE      Backup DB (default "main") to FILE
.bail on|off           Stop after hitting an error.  Default OFF
.clone NEWDB           Clone data into NEWDB from the existing database
.databases             List names and files of attached databases
.dump ?TABLE? ...      Dump the database in an SQL text format
                         If TABLE specified, only dump tables matching
                         LIKE pattern TABLE.
.echo on|off           Turn command echo on or off
.eqp on|off            Enable or disable automatic EXPLAIN QUERY PLAN
.exit                  Exit this program
.explain ?on|off?      Turn output mode suitable for EXPLAIN on or off.
                         With no args, it turns EXPLAIN on.
.fullschema            Show schema and the content of sqlite_stat tables
.headers on|off        Turn display of headers on or off
.help                  Show this message
.import FILE TABLE     Import data from FILE into TABLE
.indices ?TABLE?       Show names of all indices
                         If TABLE specified, only show indices for tables
                         matching LIKE pattern TABLE.
.load FILE ?ENTRY?     Load an extension library
.log FILE|off          Turn logging on or off.  FILE can be stderr/stdout
.mode MODE ?TABLE?     Set output mode where MODE is one of:
                         csv      Comma-separated values
                         column   Left-aligned columns.  (See .width)
                         html     HTML <table> code
                         insert   SQL insert statements for TABLE
                         line     One value per line
                         list     Values delimited by .separator string
                         tabs     Tab-separated values
                         tcl      TCL list elements
.nullvalue STRING      Use STRING in place of NULL values
.once FILENAME         Output for the next SQL command only to FILENAME
.open ?FILENAME?       Close existing database and reopen FILENAME
.output ?FILENAME?     Send output to FILENAME or stdout
.print STRING...       Print literal STRING
.prompt MAIN CONTINUE  Replace the standard prompts
.quit                  Exit this program
.read FILENAME         Execute SQL in FILENAME
.restore ?DB? FILE     Restore content of DB (default "main") from FILE
.save FILE             Write in-memory database into FILE
.schema ?TABLE?        Show the CREATE statements
                         If TABLE specified, only show tables matching
                         LIKE pattern TABLE.
.separator STRING ?NL? Change separator used by output mode and .import
                         NL is the end-of-line mark for CSV
.shell CMD ARGS...     Run CMD ARGS... in a system shell
.show                  Show the current values for various settings
.stats on|off          Turn stats on or off
.system CMD ARGS...    Run CMD ARGS... in a system shell
.tables ?TABLE?        List names of tables
                         If TABLE specified, only list tables matching
                         LIKE pattern TABLE.
.timeout MS            Try opening locked tables for MS milliseconds
.timer on|off          Turn SQL timer on or off
.trace FILE|off        Output each SQL statement as it is run
.vfsname ?AUX?         Print the name of the VFS stack
.width NUM1 NUM2 ...   Set column widths for "column" mode
                         Negative values right-justify
                         
посмотрим названия таблиц

sqlite> .tables
auth_group                  django_admin_log
auth_group_permissions      django_content_type
auth_permission             django_migrations
auth_user                   django_session
auth_user_groups            firstapp_dept
auth_user_user_permissions  firstapp_workers

проверим нашу таблицу

sqlite> .schema firstapp_workers
CREATE TABLE "firstapp_workers" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "name" text NOT NULL, "birthday" datetime NOT NU
LL, "dept_id" integer NOT NULL REFERENCES "firstapp_dept" ("id"), "boss" varchar(12) NOT NULL);
CREATE INDEX firstapp_workers_b5a9fd30 ON "firstapp_workers" ("dept_id");

выйдем

sqlite> .exit

На этом все, видео выложу на моем канале YouTube!


Комментарии пользователей

Эту новость ещё не комментировалиНаписать комментарий
Анонимам нельзя оставоять комментарии, зарегистрируйтесь!

Контакты Группа ВК Сборник материалов по Cisco, Asterisk, Windows Server, Python и Django, SQL и T-SQL, FreeBSD и LinuxКод обмена баннерами Видео к IT статьям на YoutubeВидео на другие темы Смотреть
Мои друзья: Советы, помощь, инструменты для сис.админа, статическая и динамическая маршрутизация, FreeBSD

© Snakeproject.ru создан в 2013 году.
При копировании материала с сайта - оставьте ссылку.

Рейтинг@Mail.ru
Рейтинг@Mail.ru Яндекс.Метрика





Поддержать автора и проект