2024/08/29 6

Serializer 활용하기

1. Article에 Comment 추가하기 : 모델 사이에 참조 관계가 있다면 해당 필드를 포함하거나 중첩할 수 있음 결국 우리가 조작해줘야할 것: Serializer현재 Article → Comments 접근이 필요 == 역참조역참조시 사용할 수 있는 comment_set 이 있으나 우리는 comments 로 명명from rest_framework import serializersfrom .models import Article, Commentclass CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = "__all__" read_only_fields = ("..

Web/Django 2024.08.29

Relationship과 DRF(with. particular seed)

django-seed에서 앱이 아니라 특정 모델만 지정해서 댓글 만들기!https://github.com/Brobin/django-seed python manage.py seed articles --number=20 --seeder "Comment.article_id" 2 Comment 만들어보기models.pyclass Comment(models.Model): article = models.ForeignKey( Article, on_delete=models.CASCADE, related_name="comments") content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) upda..

Web/Django 2024.08.29

DRF CBV

Class Based View 특징클래스형 뷰에서는 특정 Http Method에 대한 처리를 함수로 분리할 수 있음→ GET요청에 대한 처리는 get()에서, POST 요청에 대한 처리는 post()에서 정의 가능 Class Based View 종류APIView - DRF CBV의 베이스 클래스GenericAPIView일반적인 API 작성을 위한 기능이 포함된 클래스보통 CRUD 기능이 대부분인 상황을 위해 여러가지 기능이 미리 내장됨Mixin재사용 가능한 여러가지 기능을 담고있느 클래스말그대로 여러 클래스를 섞어서 사용하기 위한 클래스ListModelMixin - 리스트 반환 API를 만들기 위해 상속 받는 클래스CreateModelMixin - 새로운 객체를 생성하는 API를 만들기위해 상속 받는 클..

Web/Django 2024.08.29

Django Seed(Response와 Serializer)

0. 기초작업api_pjt 라는 이름의 프로젝트를 생성articles 앱을 생성하고 기본적인 url 구조를 만듦/api/v1/articles/로 들어오면 articles 앱의 urls로 연결articles 앱의 models.py를 작성Artcile 모델 클래스를 작성하고 아래 필드를 포함titlecontentcreated_atupdated_at조회를 하려면 데이터가 필요Django Seed :→ 매번 create하는 것도 너무 힘들기에 자동으로 많이 생성해주는 라이브러리 installpip install django-seed→ freeze !settings.pyINSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "djang..

Web/Django 2024.08.29

파이썬 함수(is, ==의 차이/ 바다코끼리/ suppress[try catch] / big num)

1. str# add_string_by_plus 주소가 계속 바뀜add_string_by_plus = ""for i in range(50): add_string_by_plus += str(i)print(add_string_by_plus)---------------------------------#좀더 최적화된 방식import ioadd_string_by_plus = io.StringIO()for i in range(50): add_string_by_plus.write(str(i))string_by_plus = add_string_by_plus.getvalue()print(string_by_plus)  2. try catch와 contextlib.suppress filename = "타겟.jpg..

파이썬 2024.08.29