from rest_framework import serializers
from .models import Product
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = '__all__'
์ถ์ฒ: https://www.django-rest-framework.org/api-guide/serializers/
from rest_framework import generics
from rest_framework import mixins
class ProductListAPI(generics.GenericAPIView, mixins.ListModelMixin):
serializer_class = ProductSerializer
def get_queryset(self):
return Product.objects.all().order_by('id')
def get(self, request , *args , **kwargs):
return self.list(request, *args, **kwargs)
class ProductDetailAPI(generics.GenericAPIView, mixins.RetrieveModelMixin):
serializer_class = ProductSerializer
def get_queryset(self):
return Product.objects.all().order_by('id')
def get(self, request , *args , **kwargs):
return self.retrieve(request, *args, **kwargs)
ProductListAPI
๋ ์ ํ ๋ฆฌ์คํธ๋ฅผ ๋ณด์ฌ์ฃผ๊ณ ProductDetailAPI
๋ ์ ํ ํ๋์ ๊ฐ์ฒด๋ฅผ ๋ณด์ฌ์ค๋ค.urlpatterns = [
.
.
.
path('api/product/', ProductListAPI.as_view()),
path('api/product/<int:pk>/', ProductDetailAPI.as_view()),
]
{% extends "base.html" %}
{% load humanize %}
{% block header %}
<script>
function product_detail(id) {
$.ajax({
url: "/api/product/" + id,
success: function (result) {
$("#product-" + id).popover({
html: true,
content: result.name + "<br/>" + result.price
}).popover('show');
}
});
}
function product_leave(id) {
$("#product-" + id).popover('hide');
}
$(document).ready(function () {});
</script>
{% endblock %}
{% block contents %}
<div class="row mt-5">
<div class="col-12">
<table class="table table-light">
<thead class="thead-light">
<tr>
<th scope="col">#</th>
<th scope="col">์ํ๋ช
</th>
<th scope="col">๊ฐ๊ฒฉ</th>
<th scope="col">๋ฑ๋ก๋ ์ง</th>
</tr>
</thead>
<tbody class="text-dark">
{% for product in product_list %}
<tr>
<th scope="row">{{ product.id }}</th>
<th><a id="product-{{ product.id }}" onmouseenter="product_detail({{ product.id }});"
onmouseleave="product_leave({{ product.id }});" href="/product/{{ product.id }}">{{ product.name }}</a>
</th>
<th>{{ product.price|intcomma }} ์</th>
<th>{{ product.register_date|date:'Y-m-d H:i' }}</th>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endblock %}