文章出處

上篇文章中聊了聊@property的用法,這篇文章則聊聊@property在數據庫model中的一些小技巧,同時也會涉及些Django在數據庫建模的過程中,外鍵查詢和反向查詢方面的內容。

不多說,看例子

    from django.db import models    class Person(models.Model):        name = models.CharField(max_length=64)        age = models.IntegerField()        tel = models.CharField(max_length=64)        @property        def all_cars(self):            return cars.all()        @property        def info(self):            # return the name and tel of person            return '%s %s' % (self.name, self.tel)    class Car(models.Model):        owner = models.Foreignkey(Person, related_name='cars')        name = models.CharField(max_length=64)        price = models.FloatField()

在上面的兩個表中,Person表是主表,Car是字表,Car表外鍵至Person表。
子表查詢主表:

    car = Car.objects.get(id=1)    # 查詢該車的車主    owner = car.owner

主表查詢子表,即反向查詢:

    Tom = Person.objects.get(id=1)    # 查詢此人有多少車    # 方式一:    # Django默認每個主表對象都有一個外鍵的屬性    # 可以通過它來查詢所有屬于主表的子表信息    # 查詢方式:主表.子表_set()    # 返回值為一個queryset對象    Tom.Car_set().all()    # 方式二:    # 通過在外鍵中設置related_name屬性值既可    Tom.cars.all()    # 方式三:    # 通過@property裝飾器在model中預定義方法實現    Tom.all_cars()

查詢一些自己需要的組合數據,比如獲取某人的關鍵信息

    Tom.info()

另外,在新的需求突然提出的時候,在不改動原有查詢代碼的情況下,在表模型中添加此裝飾器裝飾過的方法既可。

看文倉www.92to.com網友整理上傳,為您提供最全的知識大全,期待您的分享,轉載請注明出處。
歡迎轉載:http://www.kanwencang.com/bangong/20161219/73808.html

文章列表




Avast logo

Avast 防毒軟體已檢查此封電子郵件的病毒。
www.avast.com


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()