models.py


from django.db import models

# Create your models here.

class Post(models.Model):
title = models.CharField(max_length=30)
content = models.TextField()
create_date = models.DateTimeField(auto_now_add=True)
modify_date = models.DateTimeField(auto_now=True)

def __str__(self):
return self.title + str(self.create_date)



settings.py



# Application definition

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig',
]



PycharmProjects\django-env1>python manage.py makemigrations

Migrations for 'myapp':

  myapp\migrations\0001_initial.py

    - Create model Post


(venv) C:\PycharmProjects\django-env1>python manage.py migrate

Operations to perform:

  Apply all migrations: admin, auth, contenttypes, myapp, sessions

Running migrations:

  Applying myapp.0001_initial... OK




PycharmProjects\django-env1>python manage.py shell

Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 16:07:46) [MSC v.1900 32 bit (Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.

(InteractiveConsole)

>>> from myapp.models import Post

>>> Post

<class 'myapp.models.Post'>

>>> Post.objects.create(title='제목입니다', content='내용입니다 ')

<Post: Post object (1)>

>>> Post

<class 'myapp.models.Post'>

>>> quit()


PycharmProjects\django-env1>python manage.py shell

Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 16:07:46) [MSC v.1900 32 bit (Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.

(InteractiveConsole)

>>> from myapp.models import Post

>>> Post.objects.all()

<QuerySet [<Post: 제목입니다2018-07-25 05:49:16.567963+00:00>]>

>>> p = Post.objects.first()

>>> p

<Post: 제목입니다2018-07-25 05:49:16.567963+00:00>

>>> p.title

'제목입니다'

>>> p.content

'내용입니다 '

>>> p.create_date

datetime.datetime(2018, 7, 25, 5, 49, 16, 567963, tzinfo=<UTC>)

>>> p.modify_date

datetime.datetime(2018, 7, 25, 5, 49, 16, 567963, tzinfo=<UTC>)

>>> p.content = '내용 수정합니다.아아아'

>>> p.save()

>>> p.content

'내용 수정합니다.아아아'

>>> p.modify_date

datetime.datetime(2018, 7, 25, 5, 52, 21, 526856, tzinfo=<UTC>)

>>> post = {'title':'두번째 글 제목','content':'으하하하'}

>>> post

{'title': '두번째 글 제목', 'content': '으하하하'}

>>> Post.objects.create(**post)

<Post: 두번째 글 제목2018-07-25 05:53:48.258469+00:00>

>>> Post.objects.all()

<QuerySet [<Post: 제목입니다2018-07-25 05:49:16.567963+00:00>, <Post: 두번째 글 제목2018-07-25 05:

53:48.258469+00:00>]>

>>> for post in Post.objects.all():

...     print(post)

...

제목입니다2018-07-25 05:49:16.567963+00:00

두번째 글 제목2018-07-25 05:53:48.258469+00:00

>>> Post.objects.first()

<Post: 제목입니다2018-07-25 05:49:16.567963+00:00>

>>> Post.objects.last()

<Post: 두번째 글 제목2018-07-25 05:53:48.258469+00:00>

>>> p1 = Post.objects.first()

>>> p1

<Post: 제목입니다2018-07-25 05:49:16.567963+00:00>

>>> p2 = Post.objects.last()

>>> p2

<Post: 두번째 글 제목2018-07-25 05:53:48.258469+00:00>


id는 자동으로 생성된 값이면 pk이다. migrations에서 0001_initial.py 에서 확인 가능

operations = [
migrations.CreateModel(
name='Post',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=30)),
('content', models.TextField()),
('create_date', models.DateTimeField(auto_now_add=True)),
('modify_date', models.DateTimeField(auto_now=True)),
],
),
]


>>> p1.id

1

>>> p2.id

2

>>> Post.objects.get(id=1) == p1

True

>>> Post.objects.get(id=2) == p2

True

>>> Post.objects.get(id=3)

Traceback (most recent call last):

  File "<console>", line 1, in <module>

  File "C:\PycharmProjects\django-env1\venv\lib\site-packages\django\db\models\manager

.py", line 82, in manager_method

    return getattr(self.get_queryset(), name)(*args, **kwargs)

  File "C:\PycharmProjects\django-env1\venv\lib\site-packages\django\db\models\query.p

y", line 403, in get

    self.model._meta.object_name

myapp.models.DoesNotExist: Post matching query does not exist.

>>> Post.objects.filter(id=1)

<QuerySet [<Post: 제목입니다2018-07-25 05:49:16.567963+00:00>]>

>>> Post.objects.filter(id=3)

<QuerySet []>


filter로 조건 없이 실행하면 모든 데이터 다 불러온다. get은 하나 이상 불러오지 않고 에러 발생한다.


>>> Post.objects.filter()

<QuerySet [<Post: 제목입니다2018-07-25 05:49:16.567963+00:00>, <Post: 두번째 글 제목2018-07-25 05:

53:48.258469+00:00>]>


create_date 컬럼에서 __다음에 year가 2018인 것만 출력하라

>>> Post.objects.filter(create_date__year=2018)

<QuerySet [<Post: 제목입니다2018-07-25 05:49:16.567963+00:00>, <Post: 두번째 글 제목2018-07-25 05:

53:48.258469+00:00>]>

title 컬럼에서 __다음에 '제목'으로 시작하는 것만 출력하라 

>>> Post.objects.filter(title__startswith='제목')

<QuerySet [<Post: 제목입니다2018-07-25 05:49:16.567963+00:00>]>






'파이썬 python > django' 카테고리의 다른 글

django view , 간단한 뷰 구현  (0) 2018.07.25
starproject , 접속 확인  (0) 2018.07.19
가상환경 django 설치  (0) 2018.07.18

(venv) C:\PycharmProjects\django-env1>pip install django


(venv) C:\PycharmProjects\django-env1>pip list
DEPRECATION: The default format will switch to columns in the future. You can use --format=(legacy
|columns) (or define a format=(legacy|columns) in your pip.conf under the [list] section) to disab
le this warning.
Django (2.0.7)
pip (9.0.3)
pytz (2018.5)
setuptools (39.0.1)


(venv) C:\PycharmProjects\django-env1>django-admin startproject firstproject .


(venv) C:\PycharmProjects\django-env1>python manage.py runserver



PycharmProjects\django-env1>python manage.py startapp myapp


PycharmProjects\django-env1>python manage.py runserver 127.0.0.1:9999


PycharmProjects\django-env1>python manage.py runserver

Django version 2.0.7, using settings 'firstproject.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

firstproject 디렉토리

settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',
]
urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
path('admin/', admin.site.urls),
path('app/', include("myapp.urls")),
]

myapp 디렉토리



urls.py 

from django.urls import path
from . import views

urlpatterns = [
path("", views.say_hi)
]



views.py


from django.shortcuts import render, HttpResponse
import datetime

# Create your views here.

def say_hi(request):
now_time = str(datetime.datetime.now())
name = request.GET.get('name')
if not name:
name = '손님'
return HttpResponse("<h1>Hi {}</h1>".format(name)
+ '<br/><br/>'
+ now_time)



접속


http://127.0.0.1:8000/app/?name=whoami


결과물

Hi whoami



2018-07-25 11:34:23.509043


접속


http://127.0.0.1:8000/app/



결과물


Hi 손님



2018-07-25 11:34:59.472259



'파이썬 python > django' 카테고리의 다른 글

django model 1 sqlite3  (0) 2018.07.25
starproject , 접속 확인  (0) 2018.07.19
가상환경 django 설치  (0) 2018.07.18

PS D:\python\django1\django\Scripts> .\activate

(django) PS D:\python\django1\django\Scripts>

(django) PS D:\python\django1\django\Scripts>

(django) PS D:\python\django1\django\Scripts> .\django-admin startproject first

(django) PS D:\python\django1\django\Scripts>

(django) PS D:\python\django1\django\Scripts> dir



    디렉터리: D:\python\django1\django\Scripts



Mode                LastWriteTime     Length Name

----                -------------     ------ ----

d----      2018-07-19   오후 9:34            first

d----      2018-07-18   오후 4:10            __pycache__

-a---      2018-07-18   오후 4:05       2284 activate

-a---      2018-07-18   오후 4:05       1023 activate.bat

-a---      2018-07-18   오후 4:05       1494 Activate.ps1

-a---      2018-07-18   오후 4:05        368 deactivate.bat

-a---      2018-07-18   오후 4:10      93087 django-admin.exe

-a---      2018-07-18   오후 4:10        153 django-admin.py

-a---      2018-07-18   오후 4:04      89470 easy_install-3.6.exe

-a---      2018-07-18   오후 4:04      89470 easy_install.exe

-a---      2018-07-18   오후 4:08      93036 pip.exe

-a---      2018-07-18   오후 4:08      93036 pip3.6.exe

-a---      2018-07-18   오후 4:08      93036 pip3.exe

-a---      2018-07-18   오후 4:04     164504 pyexpat.pyd

-a---      2018-07-18   오후 4:04      97944 python.exe

-a---      2018-07-18   오후 4:04      58520 python3.dll

-a---      2018-07-18   오후 4:04    3303064 python36.dll

-a---      2018-07-18   오후 4:04      96408 pythonw.exe

-a---      2018-07-18   오후 4:04      23704 select.pyd

-a---      2018-07-18   오후 4:04     880792 sqlite3.dll

-a---      2018-07-18   오후 4:04    1307136 tcl86t.dll

-a---      2018-07-18   오후 4:04    1550336 tk86t.dll

-a---      2018-07-18   오후 4:04     896152 unicodedata.pyd

-a---      2018-07-18   오후 4:04      83784 vcruntime140.dll

-a---      2018-07-18   오후 4:04      24728 winsound.pyd

-a---      2018-07-18   오후 4:04      45720 _asyncio.pyd

-a---      2018-07-18   오후 4:04      78488 _bz2.pyd

-a---      2018-07-18   오후 4:04     102552 _ctypes.pyd

-a---      2018-07-18   오후 4:04      30360 _ctypes_test.pyd

-a---      2018-07-18   오후 4:04     216728 _decimal.pyd

-a---      2018-07-18   오후 4:04      22168 _distutils_findvs.pyd

-a---      2018-07-18   오후 4:04     163992 _elementtree.pyd

-a---      2018-07-18   오후 4:04    1121432 _hashlib.pyd

-a---      2018-07-18   오후 4:04     183960 _lzma.pyd

-a---      2018-07-18   오후 4:04      33432 _msi.pyd

-a---      2018-07-18   오후 4:04      25752 _multiprocessing.pyd

-a---      2018-07-18   오후 4:04      34456 _overlapped.pyd

-a---      2018-07-18   오후 4:04      63640 _socket.pyd

-a---      2018-07-18   오후 4:04      64664 _sqlite3.pyd

-a---      2018-07-18   오후 4:04    1459864 _ssl.pyd

-a---      2018-07-18   오후 4:04      41624 _testbuffer.pyd

-a---      2018-07-18   오후 4:04      76440 _testcapi.pyd

-a---      2018-07-18   오후 4:04      21144 _testconsole.pyd

-a---      2018-07-18   오후 4:04      19608 _testimportmultiple.pyd

-a---      2018-07-18   오후 4:04      26264 _testmultiphase.pyd

-a---      2018-07-18   오후 4:04      53400 _tkinter.pyd



(django) PS D:\python\django1\django\Scripts> cd first

(django) PS D:\python\django1\django\Scripts\first> ls



    디렉터리: D:\python\django1\django\Scripts\first



Mode                LastWriteTime     Length Name

----                -------------     ------ ----

d----      2018-07-19   오후 9:34            first

-a---      2018-07-19   오후 9:34        552 manage.py



(django) PS D:\python\django1\django\Scripts\first> python .\manage.py runserver

Performing system checks...


System check identified no issues (0 silenced).


You have 14 unapplied migration(s). Your project may not work properly until you apply the migrat

 auth, contenttypes, sessions.

Run 'python manage.py migrate' to apply them.

July 19, 2018 - 21:35:25

Django version 2.0.7, using settings 'first.settings'

Starting development server at http://127.0.0.1:8000/

Quit the server with CTRL-BREAK.

[19/Jul/2018 21:35:50] "GET / HTTP/1.1" 200 16348

[19/Jul/2018 21:35:51] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423

[19/Jul/2018 21:35:51] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 80304

Not Found: /favicon.ico

[19/Jul/2018 21:35:52] "GET /favicon.ico HTTP/1.1" 404 1971

[19/Jul/2018 21:35:52] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 81348

[19/Jul/2018 21:35:52] "GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 200 82564



(django) PS D:\python\django1\django\Scripts\first> ls



    디렉터리: D:\python\django1\django\Scripts\first



Mode                LastWriteTime     Length Name

----                -------------     ------ ----

d----      2018-07-19   오후 9:35            first

-a---      2018-07-19   오후 9:35          0 db.sqlite3

-a---      2018-07-19   오후 9:34        552 manage.py



(django) PS D:\python\django1\django\Scripts\first> cd first

(django) PS D:\python\django1\django\Scripts\first\first> ls



    디렉터리: D:\python\django1\django\Scripts\first\first



Mode                LastWriteTime     Length Name

----                -------------     ------ ----

d----      2018-07-19   오후 9:35            __pycache__

-a---      2018-07-19   오후 9:34       3205 settings.py

-a---      2018-07-19   오후 9:34        768 urls.py

-a---      2018-07-19   오후 9:34        403 wsgi.py

-a---      2018-07-19   오후 9:34          0 __init__.py



(django) PS D:\python\django1\django\Scripts\first\first> dir



    디렉터리: D:\python\django1\django\Scripts\first\first



Mode                LastWriteTime     Length Name

----                -------------     ------ ----

d----      2018-07-19   오후 9:35            __pycache__

-a---      2018-07-19   오후 9:34       3205 settings.py

-a---      2018-07-19   오후 9:34        768 urls.py

-a---      2018-07-19   오후 9:34        403 wsgi.py

-a---      2018-07-19   오후 9:34          0 __init__.py



(django) PS D:\python\django1\django\Scripts\first\first>



http://127.0.0.1:8000/

'파이썬 python > django' 카테고리의 다른 글

django model 1 sqlite3  (0) 2018.07.25
django view , 간단한 뷰 구현  (0) 2018.07.25
가상환경 django 설치  (0) 2018.07.18



PS D:\python> mkdir django1



    디렉터리: D:\python



Mode                LastWriteTime     Length Name

----                -------------     ------ ----

d----      2018-07-18   오후 4:03            django1



PS D:\python> cd .\django1

PS D:\python\django1> python -m venv django

PS D:\python\django1>

PS D:\python\django1> ls



    디렉터리: D:\python\django1



Mode                LastWriteTime     Length Name

----                -------------     ------ ----

d----      2018-07-18   오후 4:04            django



PS D:\python\django1> cd django

PS D:\python\django1\django> dir



    디렉터리: D:\python\django1\django



Mode                LastWriteTime     Length Name

----                -------------     ------ ----

d----      2018-07-18   오후 4:04            Include

d----      2018-07-18   오후 4:04            Lib

d----      2018-07-18   오후 4:05            Scripts

-a---      2018-07-18   오후 4:04        120 pyvenv.cfg



PS D:\python\django1\django> cd .\Scripts

PS D:\python\django1\django\Scripts> dir



    디렉터리: D:\python\django1\django\Scripts



Mode                LastWriteTime     Length Name

----                -------------     ------ ----

-a---      2018-07-18   오후 4:05       2284 activate

-a---      2018-07-18   오후 4:05       1023 activate.bat

-a---      2018-07-18   오후 4:05       1494 Activate.ps1

-a---      2018-07-18   오후 4:05        368 deactivate.bat

-a---      2018-07-18   오후 4:04      89470 easy_install-3.6.exe

-a---      2018-07-18   오후 4:04      89470 easy_install.exe

-a---      2018-07-18   오후 4:05      89442 pip.exe

-a---      2018-07-18   오후 4:05      89442 pip3.6.exe

-a---      2018-07-18   오후 4:05      89442 pip3.exe

-a---      2018-07-18   오후 4:04     164504 pyexpat.pyd

-a---      2018-07-18   오후 4:04      97944 python.exe

-a---      2018-07-18   오후 4:04      58520 python3.dll

-a---      2018-07-18   오후 4:04    3303064 python36.dll

-a---      2018-07-18   오후 4:04      96408 pythonw.exe

-a---      2018-07-18   오후 4:04      23704 select.pyd

-a---      2018-07-18   오후 4:04     880792 sqlite3.dll

-a---      2018-07-18   오후 4:04    1307136 tcl86t.dll

-a---      2018-07-18   오후 4:04    1550336 tk86t.dll

-a---      2018-07-18   오후 4:04     896152 unicodedata.pyd

-a---      2018-07-18   오후 4:04      83784 vcruntime140.dll

-a---      2018-07-18   오후 4:04      24728 winsound.pyd

-a---      2018-07-18   오후 4:04      45720 _asyncio.pyd

-a---      2018-07-18   오후 4:04      78488 _bz2.pyd

-a---      2018-07-18   오후 4:04     102552 _ctypes.pyd

-a---      2018-07-18   오후 4:04      30360 _ctypes_test.pyd

-a---      2018-07-18   오후 4:04     216728 _decimal.pyd

-a---      2018-07-18   오후 4:04      22168 _distutils_findvs.pyd

-a---      2018-07-18   오후 4:04     163992 _elementtree.pyd

-a---      2018-07-18   오후 4:04    1121432 _hashlib.pyd

-a---      2018-07-18   오후 4:04     183960 _lzma.pyd

-a---      2018-07-18   오후 4:04      33432 _msi.pyd

-a---      2018-07-18   오후 4:04      25752 _multiprocessing.pyd

-a---      2018-07-18   오후 4:04      34456 _overlapped.pyd

-a---      2018-07-18   오후 4:04      63640 _socket.pyd

-a---      2018-07-18   오후 4:04      64664 _sqlite3.pyd

-a---      2018-07-18   오후 4:04    1459864 _ssl.pyd

-a---      2018-07-18   오후 4:04      41624 _testbuffer.pyd

-a---      2018-07-18   오후 4:04      76440 _testcapi.pyd

-a---      2018-07-18   오후 4:04      21144 _testconsole.pyd

-a---      2018-07-18   오후 4:04      19608 _testimportmultiple.pyd

-a---      2018-07-18   오후 4:04      26264 _testmultiphase.pyd

-a---      2018-07-18   오후 4:04      53400 _tkinter.pyd



PS D:\python\django1\django\Scripts> .\activate

(django) PS D:\python\django1\django\Scripts>



(django) PS D:\python\django1\django\Scripts> pip list

Package    Version

---------- -------

pip        10.0.1

setuptools 39.0.1

(django) PS D:\python\django1\django\Scripts> pip install django

Collecting django

  Downloading https://files.pythonhosted.org/packages/ab/15/cfde97943f0db45e4f999c60b696fbb4df59e82bbccc686770f4e44c9094

/Django-2.0.7-py3-none-any.whl (7.1MB)

    100% |████████████████████████████████| 7.1MB 517kB/s

Collecting pytz (from django)

  Using cached https://files.pythonhosted.org/packages/30/4e/27c34b62430286c6d59177a0842ed90dc789ce5d1ed740887653b898779

a/pytz-2018.5-py2.py3-none-any.whl

Installing collected packages: pytz, django

Successfully installed django-2.0.7 pytz-2018.5

(django) PS D:\python\django1\django\Scripts> pip list

Package    Version

---------- -------

Django     2.0.7

pip        10.0.1

pytz       2018.5

setuptools 39.0.1

(django) PS D:\python\django1\django\Scripts>



※ 권한 문제로 윈도우에서 가상환경이 실행이 안될경우 아래명렁어 실행


cmd  ->  power shell 관리자 권한으로 실행 



Windows PowerShell

Copyright (C) 2009 Microsoft Corporation. All rights reserved.


PS C:\Users\hdcho> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned


실행 규칙 변경

실행 정책은 신뢰하지 않는 스크립트로부터 사용자를 보호해 줍니다. 실행 정책을 변경하면 about_Execution_Policies 도움말

항목에 설명된 보안 위험에 노출될 수 있습니다. 실행 정책을 변경하시겠습니까?

[Y] 예(Y)  [N] 아니요(N)  [S] 일시 중단(S)  [?] 도움말 (기본값은 "Y"임): Y







'파이썬 python > django' 카테고리의 다른 글

django model 1 sqlite3  (0) 2018.07.25
django view , 간단한 뷰 구현  (0) 2018.07.25
starproject , 접속 확인  (0) 2018.07.19

+ Recent posts