วันอังคารที่ 15 มกราคม พ.ศ. 2562

[Django] Admin Vs API


Admin หรือ Administration 
     เป็นส่วนเสริมที่ Django ให้มาพร้อมกับการสร้างโปรเจค ทำให้เราสามารถปรับแต่ง และจัดการเว็บได้สะดวกมากยิ่งขึ้น โดยการสั่งการทำงานของ admin สามารถเข้าไปตั้งค่าได้ที่ admin.py และเพิ่มคำสั่ง admin.site.register( model ที่ต้องการจัดการ ) ก็จะทำให้ สามารถจัดการตัว model นั้นๆ ผ่านหน้า admin ได้

หน้าการจัดการของ admin แสดงการจัดการ การเพิ่มคำถามและตัวเลือก


API
          API ย่อมาจาก Application Programming Interface เป็นช่องทางการเชื่อมต่อ ที่จะเชื่อมต่อกับเว็บไซต์ผู้ให้บริการ API จากที่อื่น เป็นตัวกลางที่ทำให้โปรแกรมประยุกต์เชื่อมต่อกับโปรแกรมประยุกต์อื่น หรือเชื่ิอมการทำงานเข้ากับระบบปฏิบัติการ ซึ่ง ณ ที่นี้ เราใช้ API เพื่อติดต่อกันระหว่าง command กับ โปรแกรมภาษา python ที่เราได้สร้างขึ้น 

หลังจากที่เราได้สร้าง model question และ choice ไว้เรียบร้อยแล้ว เราก็จะทำการใช้งาน API ผ่าน command 

C:\Users\user\Documents\cleverkuma>python manage.py migrate
     เป็นการบอกว่ามีการเปลี่ยนแปลงกับ model 

Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying sessions.0001_initial... OK


C:\Users\user\Documents\cleverkuma>python manage.py makemigrations pageone
Migrations for 'pageone':
  pageone\migrations\0001_initial.py
    - Create model Choice
    - Create model Question
    - Add field question to choice

               ทำการ migrations

C:\Users\user\Documents\cleverkuma>python manage.py sqlmigrate pageone 0001
BEGIN;

               สร้างฐานข้อมูล
--
-- Create model Choice
--
CREATE TABLE "pageone_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "score" integer NOT NULL);
--
-- Create model Question
--
CREATE TABLE "pageone_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "question_text" varchar(200) NOT NULL, "pub_date" datetime NOT NULL);
--
-- Add field question to choice
--
ALTER TABLE "pageone_choice" RENAME TO "pageone_choice__old";
CREATE TABLE "pageone_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "score" integer NOT NULL, "question_id" integer NOT NULL REFERENCES "pageone_question" ("id") DEFERRABLE INITIALLY DEFERRED);
INSERT INTO "pageone_choice" ("id", "choice_text", "score", "question_id") SELECT "id", "choice_text", "score", NULL FROM "pageone_choice__old";
DROP TABLE "pageone_choice__old";
CREATE INDEX "pageone_choice_question_id_b8c7a7bf" ON "pageone_choice" ("question_id");
COMMIT;


C:\Users\user\Documents\cleverkuma>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, pageone, sessions
Running migrations:
  Applying pageone.0001_initial... OK

C:\Users\user\Documents\cleverkuma>python manage.py shell   #เรียกใช้ API
Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 14:57:15) [MSC v.1915 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)

>>> from pageone.models import Choice, Question      #import Choice, Question 
>>> Question.objects.all()                                               #เรียกดู object ทั้งหมดที่มีอยู่ใน Question
<QuerySet []>                                                                  #ใน set ยังไม่มีข้อมูล
>>> from django.utils import timezone
>>> q = Question(question_text="What's up?", pub_date=timezone.now())   #create new object
>>> q.save()                                                                     #บันทึก
>>> q.id                                                                            #เรียกดูลำดับที่
1
>>> q.question_text                                                          #ดูข้อมูลใน field ที่ชื่อว่า question_text 
"What's up?"
>>> q.pub_date
datetime.datetime(2019, 1, 12, 16, 57, 21, 106777, tzinfo=<UTC>)
>>> q.question_text = "What's up?"
>>> q.save()
>>> Question.objects.all()
<QuerySet [<Question: Question object (1)>]>

>>> q = Question(question_text="What's new?", pub_date=timezone.now())  #เพิ่มคำถามที่ 3
>>> q.save()
>>> q.id
3
>>> Question.objects.filter(id=1)                                                  #ดูคำถามแรก
<QuerySet [<Question: What's up?>]>
>>> Question.objects.filter(question_text__startswith='What')   #ดูคำถามที่ขึ้นด้วย What
<QuerySet [<Question: What's up?>, <Question: What's new?>]>
>>> q.choice_set.all()                                                                    #ดูตัวเลือกทั้งหมด 
<QuerySet []>                                                                                #แสดงเป็น set ว่าง
>>> q.choice_set.create(choice_text='Not much', score=0)          #เพิ่มตัวเลือก
<Choice: Not much>
>>> q.choice_set.create(choice_text='The sky', score=0)
<Choice: The sky>
>>> c = q.choice_set.create(choice_text='Just hacking again', score=0)
>>> q.choice_set.all()                                                                     #ดูตัวเลือกทั้งหมด 
<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
>>> q.choice_set.count()                                                                #นับตัวเลือกทั้งหมด
3


--------------------------------------------------------------------
models.py


from django.db import models
from django.utils import timezone

class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')

def __str__(self):
return self.question_text

def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
score = models.IntegerField(default=0)

def __str__(self):
return self.choice_text

------------------------------------------------------------------
จะเห็นได้ว่า การใช้ API ผ่าน command จะทำให้เราเห็นการทำงานและมีความเข้าใจการทำงานของการจัดการ model แต่การใช้ admin จะเพิ่มความสะดวกให้กับเรา

สามารถศึกษาเพิ่มเติมได้ที่ https://docs.djangoproject.com/en/2.1/intro/tutorial02/

ไม่มีความคิดเห็น:

แสดงความคิดเห็น