<aside> 💡 게시판 필터 만들기
</aside>
@api_view(['GET', 'POST'])
def article_list_or_create(request):
# 게시글 전체 조회
def article_list():
# 좋아요 유저 수 column추가
articles = Article.objects.annotate(
like_count=Count('like_users', distinct=True)
).order_by('-pk')
serializers = ArticleListSerializer(articles, many=True)
return Response(serializers.data)
# 게시글 생성
def article_create():
serializers = ArticleSerializer(data=request.data)
if serializers.is_valid(raise_exception=True):
serializers.save(user_id=request.user)
return Response(serializers.data, status=status.HTTP_201_CREATED)
if request.method == 'GET':
return article_list()
elif request.method == 'POST':
return article_create()
now = datetime.now()
before_one_week = now - timedelta(weeks=1)
now = now.strftime('%Y-%m-%d')
since = before_one_week.strftime('%Y-%m-%d')
articles = Article.objects.filter(created_at__range=[since, now])
경고 발생
: warnings.warn("DateTimeField %s received a naive datetime (%s)now = timezone.now()
articles = Article.objects.filter(created_at__range=[now-timedelta(days=6), now])
# 최근 1주일 게시글, 좋아요 순으로 나열
articles = Article.objects.filter(
created_at__range=[now-timedelta(days=6), now]
).annotate(
like_count=Count('like_users', distinct=True)
).order_by('-like_count')