iT邦幫忙

2023 iThome 鐵人賽

DAY 1
0
自我挑戰組

Django系列 第 18

Day18~Django 漫漫長路-objects create資料創建必備技能

  • 分享至 

  • xImage
  •  

大家好,我是Leo
今天要來講解,django object create的幾種方式/images/emoticon/emoticon30.gif
OK~~~ Let's go now!!!


model

假設我們今天有一張table,如下圖
https://ithelp.ithome.com.tw/upload/images/20230330/201548535Tz21neS0D.png

models/init

from .doggle_model import *

models/doggle_model.py

from django.db import models
class doggle(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255,null=True,blank=True)
    sex = models.IntegerField(null=True,blank=True)
    age = models.IntegerField(null=True,blank=True)
    created_at = models.DateTimeField(auto_now_add=True, editable=False)
    updated_at = models.DateTimeField(auto_now_add=True, editable=False)

Views

views/init

from .doggle import *

views/doggle

create 第一種方式 field create

這種方式參數一多,就要寫很多欄位

from rest_framework.response import Response
from website.models import doggle
from rest_framework import permissions, views

class DoggleAPIView(views.APIView):
    permission_classes = (permissions.AllowAny,)
    authentication_classes = []

    def post(self, request):
        name = request.data.get('name',None)
        age = request.data.get('age',None)
        sex = request.data.get('sex',None)
        doggle.objects.create(
            name=name,
            age=age,
            sex=sex
        )

        return Response({"massage": True},status=201)

create 第二種方式 dict create

for 去跑參數,這邊如果request.data跟db model field name不一致時,要另行調整
透過dict的方式直接存入model內

from rest_framework.response import Response
from website.models import doggle
from rest_framework import permissions, views

class DoggleAPIView(views.APIView):
    permission_classes = (permissions.AllowAny,)
    authentication_classes = []

    def post(self, request):
        dic = dict()
        for k,v in request.data.items():
            dic[k] = v

        doggle_model = doggle.objects.create(**dic)
        doggle_model.save()

        return Response({"massage": True},status=201)

create 第三種方式 update or create

第三種方式是將update and create寫在一起
pk=request.data.get('id') -> 這欄是判斷是否要新增或修改
也就是id出現在db內有出現則修改
也可以判斷多個 ex 在下面再帶個name = request.data.get('name')

from rest_framework.response import Response
from website.models import doggle
from rest_framework import permissions, views

class DoggleAPIView(views.APIView):
    permission_classes = (permissions.AllowAny,)
    authentication_classes = []

    def post(self, request):
        dic = dict()
        for k,v in request.data.items():
            dic[k] = v

        obj, created = doggle.objects.update_or_create(
            # check same name
            pk=request.data.get('id'),
            defaults=dic,
        )
        msg = 'create' if created else 'update'
        return Response({"massage": True,"msg":msg},status=201)

urls

from django.urls import path, include, re_path
from django.conf import settings
from django.conf.urls.static import static
from website.views import (
    DoggleAPIView
)

urlpatterns = [
    path('api/doggle/create',DoggleAPIView.as_view(),name='api-doggle-create'),

] +static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

今天主要是講解create的方式,明天我們來講method的方法
我們明天見,各位掰掰~~~/images/emoticon/emoticon29.gif


上一篇
Day17~Django 漫漫長路-踏上雲的路途,架構GCP Appengine
下一篇
Day19~Django 漫漫長路- RESTful method的應用
系列文
Django30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言