2015年11月23日 星期一

Python學習筆記(四) - Advanced Django models management

Django裡,model的資料操作與查詢,可進階寫成Manager,整個詳細過程記錄如下…

一、定義Manager class:
class TempleManager(models.Manager):
    def create_temple(self,name,locateRegion,religiousBelief,masterGod,address,latitude,longitude,phone1,phone2):
        temple = self.create(name = name, locateRegion = locateRegion, religiousBelief = religiousBelief, masterGod = masterGod, address = address, latitude = latitude, longitude = longitude, phone1 = phone1, phone2 = phone2)
        return temple

    def filter_temple(self,name,locateRegion,masterGod,address):
        temple = self.filter(name = name, locateRegion = locateRegion,  masterGod = masterGod, address = address)
        return temple

    def filterByMasterGod(self, masterGod):
        temple = self.filter(masterGod = masterGod)
        return temple

    def filterByRegion(self, locateRegion):
        temple = self.filter(locateRegion = locateRegion)
        return temple



二、定義DataObject class
class TempleInfo(models.Model):
    name = models.CharField(max_length=50)
    locateRegion = models.CharField(max_length=10)
    religiousBelief = models.CharField(max_length=50)
    masterGod = models.CharField(max_length=50)
    address = models.TextField(blank=True)
    latitude = models.FloatField()
    longitude = models.FloatField()
    phone1 = models.CharField(max_length=20,blank=True)
    phone2 = models.CharField(max_length=20,blank=True)
    objects = TempleManager()

    def __unicode__(self):
        return self.name



使用範例:
        for item in templeLst:
            filterResult = TempleInfo.objects.filter_temple(name = item.name, locateRegion = item.locateRegion, masterGod = item.mastergod, address = item.location.address)
            if len(filterResult) == 0:
                templeItem = TempleInfo.objects.create_temple(name=item.name, locateRegion=item.locateRegion, religiousBelief=item.religiousBelief, masterGod=item.mastergod, address=item.location.address, latitude=item.location.latlng.lat, longitude=item.location.latlng.lng, phone1=item.phone1, phone2=item.phone2)

沒有留言: