본문 바로가기

Python_WEB/Tweetme

[Django]Tweet List View

728x90

CodingEntrepreneurs Django 강의 정리

objects.all()>

1. 모델의 모든 레코드들을 QuerySet으로 가져온다.

 

QuerySet>

1. 반복가능한(iterable) 객체

 

views.py>

# tweets/views.py

from django.http import HttpResponse, Http404, JsonResponse
from django.shortcuts import render

from .models import Tweet

# Create your views here.
def home_view(request, *args, **kwargs):
    return render(request, "pages/home.html", context={}, status=200)


def tweet_list_view(request, *args, **kwargs):
    """
    REST API VIEW
    Consume by JavaScript or Swift or Java/ios/Andriod
    return json data
    """
    qs = Tweet.objects.all()
    tweets_list = [{"id": x.id, "content": x.content} for x in qs]
    data = {"response": tweets_list}
    return JsonResponse(data)


def tweet_detail_view(request, tweet_id, *args, **kwargs):
    """
    REST API VIEW
    Consume by JavaScript or Swift or Java/ios/Andriod
    return json data
    """
    data = {
        "id": tweet_id,
    }
    status = 200

    try:
        obj = Tweet.objects.get(id=tweet_id)
        data["content"] = obj.content
    except:
        data["message"] = "Not Found"
        status = 404

    return JsonResponse(
        data, status=status
    )  # json.dumps content_type='application/json'

 

urls.py>

# tweetme2/urls.py

from django.contrib import admin
from django.urls import path, re_path  # url

from tweets.views import home_view, tweet_detail_view, tweet_list_view

urlpatterns = [
    path("admin/", admin.site.urls),
    path("", home_view),
    path("tweets/", tweet_list_view),
    path("tweets/<int:tweet_id>", tweet_detail_view),
]

 

결과물>

반응형