一對多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()
增:ide
1.外鍵id添加 spa
models.UserInfo.objects.create(username='xs',age=19,user_type_id=1)
2.直接添加外鍵的對象code
obj = models.UserType(caption='haha') obj.save() models.UserInfo.objects.create(username='xs',age=18,user_type=obj)
查:對象
正向查詢:根據userinfo查usertypeblog
result = models.UserInfo.objects.filter(user_type__caption='CTO') for item in result: print item.username,item.age,item.user_type.caption
反向查詢:根據usertype查userinfoget
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='xs') #用字段條件查詢 print '-->4',models.UserInfo.objects.filter(user_type=result) #用對象條件查詢 user_type_obj = models.UserType.objects.get(userinfo__username='xs') print '-->0',user_type_obj.caption print '-->1',user_type_obj.userinfo_set.all().count() return HttpResponse('ok')
多對多it
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)
增:io
正向增:event
admin_obj = models.HostAdmin.objects.get(username='xs') 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='xs') host_list = models.Host.objects.filter(id__lt=3) admin_obj.host.add(*host_list)
#反向添加
host_obj = model.Host.objects.get(id=3) admin_list = models.HostAdmin.objects.filter(id__gt=1) host_obj.hostadmin_set.add(*admin_list)
查:
#正向查 admin_obj = models.HostAdmin.objects.get(username='xs') 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