Django – Ninja api querystring 처리

Django ninja api 엔진을 쓰고 있는데, 쿼리스트링을 처리하는 함수를 만들려고 한다. 주소에서 파라메터를 뽑아 쓰는 것은 직관적이었는데…

역시 똑같다. 차이가 없다.

@api.get("/weapons")def list_weapons(request, limit: int = 10, offset: int = 0):    return weapons[offset: offset + limit]
  • 파라메터에 기본값을 넣고 추가해 준다. 이건 path parameter 와 완전 동일하다.
  • 호출의 형태는 아래와 같다. So, going to the URL:
  • http://localhost:8000/api/weapons
  • same as http://localhost:8000/api/weapons?offset=0&limit=10
  • http://localhost:8000/api/weapons?offset=20

기본 값을 줬기 때문에 아무것도 주지 않으면 default value 로 처리된다.

설명서가 포함된 자세한 내용은 아래 글을 참고하자.

[
Query parameters – Django Ninja
Django Ninja – Django REST framework with high performance, easy to learn, fast to code.
![](assets/images/2023/02/docs-logo.png?ssl=1)
](https://django-ninja.rest-framework.com/guides/input/query-params/)

참고로 path parameter 도 선언 부분이나 함수 사용 부분은 완전 동일하다

@api.get("/items/{item_id}")def read_item(request, item_id: int):    return {"item_id": item_id}

그냥 대충 쓰자. loose coupled 😅

Django – ORM filter NULL 체크

가장 기본이긴 한데, 막상 쓰려니 또 찾아보네

정리해두자 코드 조각으로

Name.objects.exclude(alias__isnull=True).exclude(alias__exact='')
  • __isnull = True
  • __exact = ”

Django – Form 첨부 파일 처리

폼 객체에서 파일이 넘어 올 때 처리하는 코드 일부를 남겨둔다. enctype=multipart/form-data 로 지정해서 넘어올 때 말이다.

파일 이름은 어떻게 가져오는지, 어떤 정보가 있는지 참고가 될만하다.

print(request.FILES)print(request.FILES.items())for filename, file in request.FILES.items():    print(filename, file, file.name, file.content_type, file.size)    # file = request.FILES['filename']    # file.name           # Gives name    # file.content_type   # Gives Content type text/html etc    # file.size           # Gives file's size in byte    # file.read()         # Reads file
  • request.FILES 에 첨부파일이 담겨온다
  • file.name – 파일명
  • file.content_type – 파일 타입, 첨부파일이 그림파일인 경우 유용할 듯
  • file.size – 파일 사이즈
  • file.read() – 실제 content 내용을 읽어온다.