2022. 11. 2. 08:20ㆍ스파르타코딩클럽[AI트랙 3기]/TIL
221101
aws 2주차 조금 보고, 장고심화 4주차 마무리했다. 그리고 다시 3주차 복습하는데 실습이랑 같이했다... 그렇게 어렵지는 않은데 프로젝트를 어떻게 할까나... 걱정이 태산 같다. ㅠㅠ 제발 !!
ㅁdrf 3주차 복습
1.시리얼 라이저
1)장고에서 제일 먼저 할 것 > models.py 에서 model 만들기
2)models에 데이터구조 정의하고 데이터구조대로 테이블 만들어서 디비에 저장하는 것을 장고가 해줌 >make migrations, migrate
3)orm 이용해서 crud(views.py)에서 함.
orm 없을때는 sql문을 사용
4)앞으로 모든 데이터를 json 형식으로 주고 받음. .json 형식의 파일들(딕셔너리와 비슷하게 생김.)
**실습
1)models.py 에서 article모델 만들기
*articles > models.py
class Article(models.Model):
title = models.CharField(max_length=100)
content =models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at=models.DateTimeField(auto_now=True)
2)만든 model 디비에 넣어주기
마이그레이션
3)admin 들어가서 조작 하기
*admin.py
from articles.models import Article
admin.site.register(Article)
*웹페이지(주소/admin)
슈퍼유저로 로그인
articles에서 추가해주기 (제목, 콘텐츠)
+)디비 확인하면 articles_article에 새로운 글 생성된 것 확인 가능
+)admin에서 제목으로 보이게 하기
*models.py
def __str__(self):
return str(self.title)
하면 admin에서 제목으로 정렬함.
4)article 조회하는 API만들기
(1)url먼저 만들기
*프로젝트 urls.py
path("articles/", include("articles.urls")), >>>>> from django.urls import path, include
*articles 앱 urls.py(파일을 아예 만들어줌)
프로젝트 urls.py 내용 복사 하고 맨윗줄 지우고 from django.urls import path,include만 남김
아래 path admin 날리고 새로운 것 작성
path("index/",views.index, name="index"), #views의 index라는 것을 실행 위에 from articles import views
*views.py
render는 사용하지 않으니 삭제(템플릿 돌릴때만 사용함, 맨 윗줄)
from rest_framework.response import Response 추가
def index(request):
return Resopnse("연결되었습니다.")
>>> 이렇게 해서 주소/articles/index 하면 오류남 > apiview를 받아와야함.
먼저 from rest_framework.decorators import api_view 넣어주고
def index 위에 @api_view(['GET'])하고 새로고침하면 drf 화면 정상 출력 됨.
+)@api_view(['GET'],['POST'])하면 post 할 수 있는 화면도 추가됨.
5)디비에 저장된 article 데이터를 index에 접속했을 때 보여주기
*articles > views.py
def index(request):
articles = Article.objects.all()
하고 article import 해주기 > from articles.models import Article
return Response(articles) >>> json 시리얼라이즈 안되있다고 오류남.
Response안에 str, dict등은 잘 옴. modes에 있는 것들을 새로운 dict에 담아보자고 생각할 수 있음.
articles 밑에 article = articles[0]
article_data ={
"title" : article.title,
"content":article.content,
"created_at":article.created_at,
"updated_at":article.updated_at.
}
return Resopnse(article.data)
>>>이것마저 귀찮아서 시리얼라이즈 등장
1)serializers.py 만들기
*articles > serializers.py
'스파르타코딩클럽[AI트랙 3기] > TIL' 카테고리의 다른 글
| [내일배움단 ai트랙 3기] TIL 221103 (0) | 2022.11.04 |
|---|---|
| [내일배움단 ai트랙 3기] TIL 221102 (0) | 2022.11.03 |
| [내일배움단 ai트랙 3기] TIL 221031 (0) | 2022.11.01 |
| [내일배움단 ai트랙 3기] TIL 221028 (0) | 2022.10.30 |
| [내일배움단 ai트랙 3기] TIL 221027 (0) | 2022.10.28 |