Django 注册及创建订单商品

注册功能的实现

user/views

from rest_framework.generics import GenericAPIView
from rest_framework.views import APIView

from apps.user.models import User
from apps.user.serializers import UserSerializer
from utils import ResponseMessage
from utils.jwt_auth import create_token
from utils.password_encode import get_md5


# Create your views here.
class UserApiView(APIView):
    # 注册功能的实现
    # def post(self,request):
    #     request.data["password"] = get_md5(request.data.get("password"))
    #     # 反序列化呀,把json变成一个对象  [这是关键的一句话]
    #     user_data_serializer = UserSerializer(data=request.data)
    #     user_data_serializer.is_valid(raise_exception=True)
    #     user_data = User.objects.create(**user_data_serializer.data)
    #
    #     # 序列化一下,把json返回给前端对象
    #     user_ser = UserSerializer(instance=user_data)
    #     return JsonResponse(user_ser.data)
    def post(self,request):
        # 反序列化呀,把json变成一个对象  [这是关键的一句话]
        user_data_serializer = UserSerializer(data=request.data)
        user_data_serializer.is_valid(raise_exception=True)
        user_data = user_data_serializer.save()

        # 序列化一下,把json返回给前端对象
        user_ser = UserSerializer(instance=user_data)
        # return JsonResponse(user_ser.data)
        return ResponseMessage.UserResponse.success(user_ser.data)

user/urls

from django.urls import path
from .views import UserApiView

urlpatterns = [
    path("",UserApiView.as_view()),
]

user/serializers.py

import datetime

from rest_framework import serializers
from rest_framework.validators import UniqueValidator

from apps.user.models import User
from utils.password_encode import get_md5


class UserSerializer(serializers.ModelSerializer):
    # email作为用户名进行登录,这里我们需要做一个唯一性的验证
    email = serializers.EmailField(
        required=True,
        allow_blank=False,
        validators=[UniqueValidator(queryset=User.objects, message="用户已经存在了")]
    )
    password = serializers.CharField(write_only=True)
    # password = serializers.CharField()
    birthday = serializers.DateTimeField("%Y-%m-%d %H:%M:%S")
    create_time = serializers.DateTimeField("%Y-%m-%d %H:%M:%S",required=False)
    # create方法会被自动调用,这里可以做一些数据的验证或者是存储之前数据的加工
    def create(self, validated_data):
        print("create方法被调用了")
        print(validated_data)
        validated_data["password"] = get_md5(validated_data["password"])
        validated_data["create_time"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        result = User.objects.create(**validated_data)
        return result

    class Meta:
        model = User
        fields = "__all__"

utils/password_encode.py

import hashlib
def get_md5(param):
    md5 = hashlib.md5()
    md5.update(param.encode())
    return md5.hexdigest()


urls

path("user/", include("user.urls")),

Django 注册及创建订单商品_第1张图片

用户个人中心获取 用户信息接口开发

class UserApiView(APIView):
    

    def get(self, request):
        email = request.GET.get("email")
        try:
            user_data = User.objects.get(email=email)
            user_ser = UserSerializer(user_data)
            return ResponseMessage.UserResponse.success(user_ser.data)
        except Exception as e:
            print(e)
            return ResponseMessage.UserResponse.failed("用户信息获取失败")

Django 注册及创建订单商品_第2张图片

订单逻辑梳理与表的创建

Django 注册及创建订单商品_第3张图片
Django 注册及创建订单商品_第4张图片
Django 注册及创建订单商品_第5张图片
Django 注册及创建订单商品_第6张图片

订单商品表(点击去结算)
Django 注册及创建订单商品_第7张图片

订单表(提交订单)
Django 注册及创建订单商品_第8张图片
将数据库创建的表映射到本地模型类

python manage.py inspectdb --database default goods > apps/order/models.py

基于GenericAPIView视图的调用逻辑实现创建订单商品的接口开发

order/views

from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from rest_framework.generics import GenericAPIView
from apps.order.models import OrderGoods
from apps.order.serializers import OrderGoodsSerializer


class OrderGoodsGenericAPIView(GenericAPIView):
    queryset = OrderGoods.objects
    serializer_class = OrderGoodsSerializer

    def post(self, request):
        # trade_no = request.data.get("trade_no")
        # print(self.get_queryset())
        # print(self.get_serializer())
        print(request.data)
        # request.data 类型是 dict   转成object传data
        ser = self.get_serializer(data=request.data)
        ser.is_valid()
        ser.save()
        return JsonResponse("ok",safe=False)

order/urls

from django.contrib import admin
from django.urls import path
from .views import OrderGoodsGenericAPIView


urlpatterns = [
    path("goods/",OrderGoodsGenericAPIView.as_view()),


]


order/serializers.py

from rest_framework import serializers
from apps.order.models import OrderGoods


class OrderGoodsSerializer(serializers.ModelSerializer):
    class Meta:
        model = OrderGoods
        fields = "__all__"

from django.db import models


class Order(models.Model):
    email = models.CharField(max_length=255, blank=True, null=True)
    order_amount = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
    address_id = models.IntegerField(blank=True, null=True)
    pay_status = models.CharField(max_length=155, blank=True, null=True)
    pay_time = models.DateTimeField(blank=True, null=True)
    ali_trade_no = models.CharField(max_length=255, blank=True, null=True)
    is_delete = models.PositiveIntegerField(blank=True, null=True)
    create_time = models.DateTimeField(blank=True, null=True)
    update_time = models.DateTimeField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'order'


class OrderGoods(models.Model):
    trade_no = models.CharField(max_length=255, blank=True, null=True)
    sku_id = models.CharField(max_length=255, blank=True, null=True)
    goods_num = models.IntegerField(blank=True, null=True)
    # create_time = models.DateTimeField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'order_goods'

urls

path("order/", include("order.urls")),

Django 注册及创建订单商品_第9张图片

基于GenericAPIView视图调用逻辑实现获取订单商品接口开发

order/view.py

class OrderGoodsGenericAPIView(GenericAPIView):
    queryset = OrderGoods.objects
    serializer_class = OrderGoodsSerializer

    def post(self, request):
        print(request.data)
        # request.data 类型是 dict   转成object传data
        ser = self.get_serializer(data=request.data)
        ser.is_valid()
        ser.save()
        return JsonResponse("ok",safe=False)

    lookup_field = "trade_no"
    def get(self, request, trade_no):
        # 这一行代码就实现了数据库里所有数据的查询   self.get_queryset()拿到配置模型表中的所有数据  返回所有数据
        # 调用self.get_serializer 其实就是调用 serializer_class = OrderGoodsSerializer
        # return JsonResponse(self.get_serializer(instance=self.get_queryset(),many=True).data,safe=False)
        print(trade_no)
        # self.get_object() 调用该方法拿到lookup_field作为请求的参数直接传进去 其实就是加了某一个条件 返回一条数据
        ser = self.get_serializer(instance=self.get_object(), many=False)
        # 传many会报错
        # ser = self.get_serializer(instance=self.get_object(),many=True)
        return JsonResponse(ser.data, safe=False)

Django 注册及创建订单商品_第10张图片

你可能感兴趣的:(Django,django,python,后端)