Kia ora,我是Charlie!
在Day09當中我們完成了用戶服務的修改資料,而今天我們要完成商品模塊的總商品資料API。
================================◉‿◉=================================
首先是url路徑的部分,一樣在ur當中包含product的url:
# products\urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$',views.product)
]
# keyboardmarket\urls.py
url('product',include('product.urls'))
# product\views.py
def product(request):
return R.ok("call success")
建立完後,我們先建立返回全部商品的API,這裡我們使用GET,首先先在Product model當中建立toJson方法:
class Product(models.Model):
id = models.AutoField(primary_key = True)
name = models.CharField(max_length = 255,verbose_name = "商品名稱")
price = models.IntegerField(verbose_name = "價格")
stored_amount = models.IntegerField(verbose_name = "存量")
created_time = models.DateTimeField(auto_now = True)
modified_time = models.DateTimeField(auto_now = True)
status = models.IntegerField(verbose_name = "狀態")
img = models.ImageField(upload_to = "productImage/")
category = models.IntegerField(verbose_name = "種類")
info = models.TextField(verbose_name = "詳細描述")
def toJson(self):
data = {}
data["name"] = self.name
data["price"] = self.price
data["stored_amount"] = self.stored_amount
data["created_time"] = self.created_time
data["modified_time"] = self.modified_time
data["status"] = self.status
data["img"] = self.img.url
data["category"] = self.category
data["info"] = self.info
return data
class Meta:
db_table = "products"
接著建立視圖,篩選出狀態為1(activate)的商品:
from tools.R import R
from .models import Product
from tools.db import ProductStatus
# Create your views here.
def product(request):
if request.method == "GET":
products = Product.objects.filter(status = ProductStatus.activate.value)
products = [i.toJson() for i in products]
return R.ok(products)
測試成功的話,就可以看到所有的商品:
接著我們還需要另外一個API接口:返回各種種類的商品API。
首先在urlpatterns裡面建立url:
url(r'/(?P<categoryID>[\w]{1,55})$',views.product),
然後在tools\db.py中的ProductCategory中,建立static method list:
@staticmethod
def list():
return list(map(lambda c: c.value, ProductCategory))
接著在views當中建立API,過濾出符合categoryID的商品:
from tools.db import ProductStatus,ProductCategory
if request.method == "GET" and categoryID is not None:
if int(categoryID) not in ProductCategory.list():
return R.badRequest("category ID does not exist")
products = Product.objects.filter(status = ProductStatus.activate.value).filter(category = categoryID)
products = [i.toJson() for i in products]
return R.ok(products)
這裡要注意的是,傳入的categoryID為String,如果直接判斷是否在ProductCategory.list當中
的話會出錯,必須要加上int()轉型才行,可以將兩者印出看看type:
print(type(categoryID))
print(type(ProductCategory.list()[0]))
而這裡還衍生了另外一個問題,如果categoryID是文字的話,轉為int就會出錯,所以這裡要再加上防堵的程式碼:
if not categoryID.isdigit():
return R.badRequest("categoryID is number only!")
最後是返回種類的API,由於我們一開始並沒有建立cateogry表及外連,在最小的更動下可以使用Enum中的value來返回,首先先建立urlpattern:
url(r'/category$',views.product),
接著在Enum當中建立dict方法:
@staticmethod
def dict():
return {
"鍵盤":ProductCategory.keyboard.value,
"耳機":ProductCategory.earphone.value,
"滑鼠":ProductCategory.mouse.value,
"桌機":ProductCategory.desktop.value
}
接著在views當中建立API:
if 'category' in request.path:
return R.ok(ProductCategory.dict())
就可收到種類。
================================◉‿◉=================================
Day10結束了!在今天我們先完成了商品的返回資料API,明天我們將完成商品資料的前端顯示,之後也會再更動cateogry的部分,讓category能夠從資料庫撈取,See ya next day!