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

+ Recent posts