[Django] 조회 쿼리 set

형이·2023년 11월 14일

Python

목록 보기
31/34
post-thumbnail

📝 Django

🖥️ 1. 조회 쿼리 set

1-1. 모든 객체 조회

posts = Post.objects.all

1-2. 특정 조건을 만족하는 객체 조회

posts = Post.objects.filter(title='django')

1-3. 일치하는 객체 하나 조회 (단일 객체)

post = Post.objects.get(title='django')

1-4. 조건을 만족하는 객체 개수 조회

count = Post.objects.filter(category=None).count()

1-5. 정렬된 객체 조회

  • 작성일 기준 내림차순으로 정렬된 포스트 조회
posts = Post.objects.order_by('-create_at')

1-6. 일부 객체만 조회 (페이징)

  • 처음 10개를 조회
posts = Post.objects.all()[:10]

1-7. 특정 필드만 선택해서 조회

  • 제목만 조회
posts = Post.objects.values('title')

1-8. 중복된 객체 제거

distinct_titles = Post.objects.values('title').distinct()

1-9. 특정 기간동안 객체 조회

posts = Post.objects.filter(create_at__range=(start_date, end_date))

0개의 댓글