python——Django(ORM連表操作)


  千呼萬喚始出來~~~當當當,終於系統要寫django的ORM操作啦!!!這里記錄的是django操作數據庫表一對多、多對多的表創建及操作。對於操作,我們只記錄連表相關的內容,介紹增加數據和查找數據,因為能查到就可以用常規方法進行修改,怎么加進來就怎么刪掉,都是大同小異,就不再贅述了~~~

一對多

class UserType(models.Model):
caption = models.CharField(max_length=32)

class UserInfo(models.Model):
user_type = models.ForeignKey(UserType)# user_type對象中封裝id,caption
username = models.CharField(max_length=32)
age = models.IntegerField()

增:

1.外鍵id添加 

models.UserInfo.objects.create(username='Eva_J',age=18,user_type_id=1)

 

2.直接添加外鍵的對象

obj = models.UserType(caption='test')
obj.save()
models.UserInfo.objects.create(username='Eva_J',age=18,user_type=obj)

查:

  正向查詢:根據userinfo查usertype

result = models.UserInfo.objects.filter(user_type__caption='CEO')
for item in result:
print item.username,item.age,item.user_type.caption

  反向查詢:根據usertype查userinfo

result = models.UserType.objects.get(id=1)
    print '-->0',result
    print '-->1',result.userinfo_set
    print '-->2',result.userinfo_set.all()
    print '-->3',result.userinfo_set.filter(username='eva') #用字段條件查詢
    print '-->4',models.UserInfo.objects.filter(user_type=result) #用對象條件查詢

    user_type_obj = models.UserType.objects.get(userinfo__username='eva')
    print '-->0',user_type_obj.caption
    print '-->1',user_type_obj.userinfo_set.all().count()
    return HttpResponse('ok')

多對多

class Host(models.Model):
    hostname = models.CharField(max_length=32)
    port = models.IntegerField()

class HostAdmin(models.Model):
    username = models.CharField(max_length=32)
    email = models.CharField(max_length=32)
    host = models.ManyToManyField(Host)

 增:

  正向增:

admin_obj = models.HostAdmin.objects.get(username='alex')
host_list = models.Host.objects.filter(id__lt=3)
admin_obj.host.add(*host_list)

  反向增:

host_obj = models.Host.objects.get(id=3)
admin_list= models.HostAdmin.objects.filter(id__gt=1)
host_obj.hostadmin_set.add(*admin_list)

       區別總結:區別在於正向查擁有自己創建好的host句柄,可以直接使用add方法添加,而反向查沒有,所以要使用django為我們提供的set句柄。

       

 查:

#正向查
    admin_obj = models.HostAdmin.objects.get(username='alex')
    print admin_obj.host.all()
 #反向查
    host_obj = models.Host.objects.get(id=3)
    print host_obj.hostadmin_set.all()

 

class Host1(models.Model):
    hostname = models.CharField(max_length=32)
    port = models.IntegerField()

class HostAdmin1(models.Model):
    username = models.CharField(max_length=32)
    email = models.CharField(max_length=32)
    host = models.ManyToManyField(Host1,through='HostRelation')

class HostRelation(models.Model):
    host =models.ForeignKey(Host1)
    admin =models.ForeignKey(HostAdmin1)
自定義多對多表創建
    #
    #models.HostRelation.objects.create(host_id=1,admin_id=1)
    #
    relationList = models.HostRelation.objects.all()
    for item in relationList:
        print item.host.hostname
        print item.admin.username
自定義多對多表操作

 

其他(selecte_related && query):

   select_related是用來為連表查詢做優化的,我們在查詢外鍵關聯的表的時候,都應該使用select_related,這樣,只需要執行一條命令就可以把相關的字段都查到了。下面就來看看select_related的作用吧~

 例:    

 1 class UserType(models.Model):
 2           caption = models.CharField(max_length=32)
 3           def __unicode__(self):
 4               return self.caption
 5 
 6 
 7       class UserInfo(models.Model):
 8           user_type = models.ForeignKey(UserType)# user_type對象中封裝id,caption
 9           username = models.CharField(max_length=32)
10           age = models.IntegerField()
11           def __unicode__(self):
12              return self.username
表結構

 

python代碼: 

result = models.UserInfo.objects.all()
      result_sr = models.UserType.objects.select_related().all()
      print result.query
      print result_sr.query

生成的sql:

      SELECT "app01_userinfo"."id", "app01_userinfo"."user_type_id", "app01_userinfo"."username", "app01_userinfo"."age" FROM "app01_userinfo"
      SELECT "app01_usertype"."id", "app01_usertype"."caption" FROM "app01_usertype"

  這里順便再介紹一下query方法,可以獲取到django為我們生成的sql內容~就是這么炫酷!

其他(F和Q):

 未完待續......


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM