Showing posts with label Database. Show all posts
Showing posts with label Database. Show all posts

Sunday, September 26, 2010

Learning Django: Data access

หลังจากที่เรา sync database แล้วเราก็สามารถจัดการ database ได้ ในตอนนี้เราจะยกตัวอย่างวิธีการจัดการ database ผ่านทาง shell python ของ Django

เริ่มต้นโดยใช้คำสั่ง

python manage.py shell

เป็นการเรียก python shell โดยใช้ environment ของ project นี้ (mysite)

ลองดูคำสั่งเหล่านี้


>>> from books.models import Publisher
>>> p1 = Publisher(name='Apress', address='2855 Telegraph Avenue',
...    city='Berkeley', state_province='CA', country='U.S.A.',
...    website='http://www.apress.com/')
>>> p1.save()
>>> p2 = Publisher(name="O'Reilly", address='10 Fawcett St.',
...    city='Cambridge', state_province='MA', country='U.S.A.',
...    website='http://www.oreilly.com/')
>>> p2.save()
>>> publisher_list = Publisher.objects.all()
>>> publisher_list
[, ]

เป็นการสร้าง object แบบ Publisher สองตัว (p1,p2) โดยแล้วใส่ลงใน database โดย method ที่ชื่อ save
ถ้าเราใส่ข้อมูลลงใน database เลยเราสามารถใช้คำสั่ง ต่อไปนี้แทนได้


>>> p1 = Publisher.objects.create(name='Apress',
... address='2855 Telegraph Avenue',
... city='Berkeley', state_province='CA', country='U.S.A.',
... website='http://www.apress.com/')
>>> p2 = Publisher.objects.create(name="O'Reilly",
... address='10 Fawcett St.', city='Cambridge',
... state_province='MA', country='U.S.A.',
... website='http://www.oreilly.com/')

สังเกตว่า publisher_list แสดงค่าออกมาเป็น [, ] ซึ่งอ่านเข้าใจลำบาก เราจะแก้ไข method __unicode__(self) ของ model ต่างๆ เพื่อให้อ่านเข้าใจง่ายขึ้น (คล้ายกับการ override function toString())

ผลจากการแก้ไข models.py


from django.db import models


class Publisher(models.Model):
    name = models.CharField(max_length=30)
    address = models.CharField(max_length=50)
    city = models.CharField(max_length=60)
    state_province = models.CharField(max_length=30)
    country = models.CharField(max_length=50)
    website = models.URLField()
    
    def __unicode__(self):
        return self.name


class Author(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)
    email = models.EmailField()
    
    def __unicode__(self):
        return u'%s %s' % (self.first_name, self.last_name)


class Book(models.Model):
    title = models.CharField(max_length=100)
    authors = models.ManyToManyField(Author)
    publisher = models.ForeignKey(Publisher)
    publication_date = models.DateField()


    def __unicode__(self):
        return self.title

หลังจากแก้ไขแล้วเราลองมาดูความเปลี่ยนแปลง(ออกจาก shell แล้วเข้าใหม่)


>>> from books.models import Publisher
>>> publisher_list = Publisher.objects.all()
>>> publisher_list
[, ]


ลองมาดู database operation เบื้องต้น ใน Django
1. การ insert และ update data
- สร้าง record

>>> p = Publisher(name='Apress',
... address='2855 Telegraph Ave.',
... city='Berkeley',
... state_province='CA',
... country='U.S.A.',
... website='http://www.apress.com/')
- insert record
>>> p.save()
- change record
>>> p.name = 'Apress Publishing'
- update record
>>> p.save()

2. select record
- select all

>>> Publisher.objects.all()
[, ]

- select with where clause

>>> Publisher.objects.filter(name='Apress')
[]


>>> Publisher.objects.filter(country="U.S.A.", state_province="CA")
[]


>>> Publisher.objects.filter(name__contains="press")
[]

3. select single record

>>> Publisher.objects.get(name="Apress")


4. select with order

>>> Publisher.objects.order_by("name")
[, ]


>>> Publisher.objects.order_by("state_province", "address")
[, ]


>>> Publisher.objects.order_by("-name")
[, ]

5. select with where and order

>>> Publisher.objects.filter(country="U.S.A.").order_by("-name")
[, ]

6. select with limit

>>> Publisher.objects.order_by('name')[0]


>>> Publisher.objects.order_by('name')[0:2]

7. update record
>>> Publisher.objects.filter(id=52).update(name='Apress Publishing')

>>> Publisher.objects.all().update(country='USA')

8. remove record

>>> p = Publisher.objects.get(name="O'Reilly")
>>> p.delete()
>>> Publisher.objects.all()
[]

Learning Django: Configuring Database


Configuring the Database


สิ่งที่เป็นจุดเด่นของ Django คือการ สร้าง Database driven application ได้ง่าย โดยอาศัย framework แบบ MTV (คล้ายๆ MVC) ทั้งนี้เนื่องจากพื้นฐานของ Django เป็น python ดังนั้นเราสามารถใช้คำสั่ง sql ในการติดต่อกับ database ได้ โดยอาศัย template, กับ view ดูตัวอย่าง code


from django.shortcuts import render_to_response
import MySQLdb

def book_list(request):
    db = MySQLdb.connect(user='me', db='mydb', passwd='secret', host='localhost')
    cursor = db.cursor()
    cursor.execute('SELECT name FROM books ORDER BY name')
    names = [row[0] for row in cursor.fetchall()]
    db.close()
    return render_to_response('book_list.html', {'names': names})

แน่นอนว่า Django วิธีที่จะจัดการส่วนที่ซ้ำซ้อนพวกนี้ (เช่นการสร้าง query, การเปิดปิด connection)
เรามาเริ่มต้นที่การ config database



เพื่อความง่ายในบทความนี้จะใช้ database engine SQLite3 ที่มากับตัว python 2.5+ ดังนั้น หลังจากนั้นแก้ค่าตัวแปร  DATABASE ที่อยู่ใน settings.py ดังนี้

- ENGINE = 'django.db.backends.sqlite3'
- NAME = ตั้งค่าเป็น full path file ที่เราจะใช้เก็บฐานข้อมูล

นอกนั้นไม่ต้องตั้งค่า(สำหรับ SQLite3)