Django筆記-Models

來源:互聯網
上載者:User

models例子如下,本文主要針對該例子來描述
from django.db import models

# Create your models here.
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 "name:%s, address:%s" % (self.name, self.address)
 
class Author(models.Model):
 first_name = models.CharField(max_length = 30)
 last_name = models.CharField(max_length=40)
 email = models.EmailField(blank=True)
 
 def __unicode__(self):
  return self.last_name
 
class Book(models.Model):
 tille = models.CharField(max_length=100)
 authors = models.ManyToManyField(Author)
 publisher = models.ForeignKey(Publisher)
 publication_date = models.DateField()
 
 def __unicode__(self):
  return self.tille

 

     1.基本操作
from website.app import models

1)insert
p1 = models.Publisher(name='Apress', address='2855 Telegraph Avenue',
     city='Berkeley', state_province='CA', country='U.S.A.',
     website='http://www.apress.com/')
p1.save()

2)select
publisher_list = models.Publisher.objects.all()
publisher_No.1 = models.Publisher.objects.all()[0:2]

3)update
p = models.Publisher.objects.all()[0]#取出第一條記錄的指標
p.name="hongxing"#將名字改為hongxing
p.save()#儲存

4)filter
models.Publisher.objects.filter(name='hongxing')#單條件搜尋
models.Publisher.objects.filter(name="chubanshe",city='beijing')#and條件
mdoels.Publisher.objects.filter(name='hognxing').update(city='zaozhuang')

5)like
models.Publisher.objects.filter(name__contains='hong')#所有名字中包含hong的記錄

6)retrieving single objects
models.Publisher.objects.get(name="hongxing")

7)order
models.Publisher.objects.order_by('name')
models.Publisher.objects.order_by('name', 'city')
models.Publisher.objects.order_by('-name')#倒序

指定預設的排序方式:
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 Meta:
     ordering=['name']
   
8)Chaining Lookups
mdoels.Publisher.objects.filter('name').order_by('city')

9)delete
models.Publisher.objects.get(name='hognxing').delete()

 

2.Foreign Key

1)ForeignKey用來定義多對一得關係,ForeignKey的參數是主鍵的類,就像文章開始
用的例子,Book.publisher的ForeignKey參數就是Publisher類。

2)對象也可以和自身關聯,用mdels.ForeignKey('self'),這樣就建立了一種遞迴關係。

3)在2)中用到了字串,是的,外鍵參數可以用字串的,這個在參數類還沒有定義的時候
尤其適用,比如在Publisher類沒有定義時,你完全可以用models.ForeignKey('Publisher')
注意:只能對同一個models.py檔案中的模型適用字串引用,其他的或者匯入的模型不可用。

4)訪問
在文章開始給出的models可以看出,Book中有外鍵publisher
如下代碼所示,通過book的object訪問publisher同訪問正常field沒區別。
但是通過主鍵Publisher訪問book時,需要用book_set的形式。
即:主鍵中模型類名的小寫+_set

>>> from website.books import models
>>> b = models.Book.objects.get(tille='djangobook')
>>> p=models.Publisher.objects.filter(name='Apress')[0]
>>> b.publisher
<Publisher: name:Apress, address:2855 Telegraph Avenue>
>>> p.book_set.all()
[<Book: djangobook>, <Book: pythonbook>]
 
    3.ManyToMany
1)ManyToManyField放在哪個模型中
分析文章開始給出的例子:一個作者可以寫多本書,一本書可以有多本書
這個Field放在Book中還是Author中都可以。但是不能兩個都放。

2)關於自關聯以及字串參數等同ForeignKey一樣。

3)訪問同ForeignKey類似
這裡說明一點。book_set屬性一定是author的一條記錄而不能是QuerySet

正向訪問:
>>> book = models.Book.objects.get(tille='djangobook')
>>> book.authors.all()
[<Author: yonggao>, <Author: xiuqi>]
反向訪問:
>>> aut = models.Author.objects.filter(last_name__contains='yonggao')
>>> aut.book_set.all()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'QuerySet' object has no attribute 'book_set'
>>>
>>> aut = aut[0]
>>> aut.book_set.all()
[<Book: djangobook>, <Book: pythonbook>]
 
   4.修改資料庫模型
建立好資料庫後,如果在添加和刪除列,python manage.py syncdb就不起作用了。
本節主要學些關於修改資料庫列的知識。
1)django對models和database同步處理,這裡直接引用原文更好些:
■Django will complain loudly if a model contains a field that has not yet been created in the
database table. This will cause an error the first time you use the Django database API to query
the given table (i.e., it will happen at code execution time, not at compilation time).
■Django does not care if a database table contains columns that are not defined in the model.
■Django does not care if a database contains a table that is not represented by a model.

2)變更欄位
在添加欄位時,可以現在models.py中添加上要添加的內容
然後通過python manage.py sqlall books來看books app中資料庫建立
語句,這樣根據sql語句,可以很輕鬆的使用alter命令來修改自己的資料庫。

    5.Managers
Book.objects.all()中objetcs就是一個Manager的例子。那麼什麼時候需要
定製自己的manager呢: to add extra manager methods, and/or
to modify the initial QuerySet the manager returns.

1)Adding Extra Manager Methods
例子:
給Book Model添加一個可以統計指定關鍵字個數的方法

class BookManager(models.Manager):
 def title_count(self,keyword):
  return self.filter(tille__icontains=keyword).count()

class Book(models.Model):
 tille = models.CharField(max_length=100)
 authors = models.ManyToManyField(Author)
 publisher = models.ForeignKey(Publisher)
 publication_date = models.DateField()
 objects = BookManager()
 
 def __unicode__(self):
  return self.tille
  
2)Modifying Initial Manager QuerySets
管理器預設的QuerySet返回表中的所有記錄,如果有需要可以定製返回內容。
只需要重寫Manager.get_query_set()就可以了。
舉例:下面的model如果用dahl管理器則在使用Book.dahl_ojbects.all()時
只會返回所有yonggao寫的書。

from django.db import models

# First, define the Manager subclass.
class DahlBookManager(models.Manager):
    def get_query_set(self):
        return super(DahlBookManager, self).get_query_set().filter(author='yonggao')

# Then hook it into the Book model explicitly.
class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=50)
    # ...

    objects = models.Manager() # The default manager.
    dahl_objects = DahlBookManager() # The Dahl-specific manager.
   
上面例子的注意點:
當自己定義管理器時,請總要保留models.Manager()這個預設管理器。

自訂管理器可以用來定義共通的過濾器例如下面的例子,使用不同的
Manager來管理不同的資料更容易。

class MaleManager(models.Manager):
    def get_query_set(self):
        return super(MaleManager, self).get_query_set().filter(sex='M')

class FemaleManager(models.Manager):
    def get_query_set(self):
        return super(FemaleManager, self).get_query_set().filter(sex='F')

class Person(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    sex = models.CharField(max_length=1, choices=(('M', 'Male'), ('F', 'Female')))
    people = models.Manager()
    men = MaleManager()
    women = FemaleManager()

一個注意點:如果在model中定義了多個manager,則第一個manager是django的預設
管理器。django的很多部分會用預設manager來處理model。

 

     6.Executing Raw SQL Queries
你可以再django使用標準的python資料庫語句。

另外,推薦方法是將sql statemets放在model methods活manager methods中。
例子:
from django.db import connection, models

class PersonManager(models.Manager):
    def first_names(self, last_name):
        cursor = connection.cursor()
        cursor.execute("""
            SELECT DISTINCT first_name
            FROM people_person
            WHERE last_name = %s""", [last_name])
        return [row[0] for row in cursor.fetchone()]

class Person(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    objects = PersonManager()

 <本節完>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.