วันศุกร์ที่ 11 มกราคม พ.ศ. 2562

[Django] models

models

- ประกอบไปด้วย database table ในรูปแบบของ class ในภาษา Python โดยผู้ใช้จะสามารถใช้ในการสร้าง, เรียกดูข้อมูล,อัพเดตข้อมูล, และ ลบข้อมูลที่อยู่ใน database โดยสามารถใช้งานผ่าน Python code ที่ใช้งานได้ง่าย
- เป็นการเชื่อมต่อกับฐานข้อมูลเพื่อจัดการการจัดเก็บข้อมูล
- มีการระบุ Field เช่น
     CharField ข้อมูลเป็นตัวอักษร
     DateTimeField ข้อมูลเป็นวันที่

ทดลองใช้งาน
1.สร้าง class ใน models.py


from django.db import models
class Poll(models.Model):
       question_text = models.CharField(max_length=200)
       pub_date = models.DateTimeField('date published')

class Choice(models.Model):
       question = models.ForeignKey(Poll)
       choice_text = models.CharField(max_length=200)



       votes = models.IntegerField(default=0)

-------------
models.Model     เรียกใช้ความสามารถของ models.Model
question_text = models.CharField    สร้างเขตข้อมูลที่ชื่อว่า question_text ในรูปแบบของเขตข้อมูลที่เป็นตัวอักษร
max_length=200     มีความยาวไม่เกิน 200 ตัวอักษร
question = models.ForeignKey(Poll)    บอกว่า choice ที่สร้างขึ้นเป็นของ Poll ไหน
-------------

2. แก้ไข settings.py

INSTALLED_APPS = [
     'django.contrib.admin',
     'django.contrib.auth',
     'django.contrib.contenttypes',
     'django.contrib.sessions',
     'django.contrib.messages',
     'django.contrib.staticfiles',
     'hello.apps.HelloConfig',
     ]

เพิ่ม app ของเราลงไปในส่วน INSTALLED_APPS เพื่อเป็นการบอกให้โปรเจครู้จัก app

3. เปิด command และ run คำสั่งเพื่อให้ class ที่สร้างขึ้นถูกเรียกใช้งาน

Run >> python manage.py makemigrations
  บอก Django ว่ามีการเปลี่ยนแปลงใน models
Run >> python manage.py migrate
ทำให้ฐานข้อมูลเกิดการเปลี่ยนแปลง

4. ทดสอบการทำงานผ่าน command

Run >>  python manage.py shell
  เป็นการใช้ API ออกคำสั่งกับ Django ให้ทำการติดต่อกับ database
Run >>  from polls.models import Poll, Choice 
  เป็นการเรียกใช้ class Poll,Choice
Run >>  Poll.objects.all()
  เรียกค่าที่อยู่ใน objects ของ Poll ในตอนแรกจะไม่แสดงค่าใดๆ เนื่องจากยังไม่มีการใส่ข้อมูลลงไป

ทดลองทำการใส่ค่าลงไป
            from django.utils import timezone                    # import timezone
            p = Poll(question="What’s new?", pub_date=timezone.now())   #ทำการ set ค่า question และ pub_date ใน class Poll
            p.save()                                                              #จัดเก็บค่า p
            p.id                                                                     #คำสั่งแสดงค่า id ของ p                  
            p.question                                                          #แสดงค่า question ที่ได้ทำการ set                                  p.pub_date                                                         #แสดง pub_date ที่ได้ทำการ set               
            p.question = "What’s up?"                                #เปลี่ยนค่า question
            p.save()                                                             #บันทึกข้อมูล

---------------------

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

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