码迷,mamicode.com
首页 > 其他好文 > 详细

djanjo ORM 一对多、多对多

时间:2016-04-23 13:12:23      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:

一、表操作之一对多

定义表结构:定义了UserType、两张表UserInfo,如下:

from django.db import models

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()

向表中添加数据:

UserType表如数据如下:
1    CTO
2    CEO
3    COO


UserInfo表中数据如下:
1    alex01    88    1
6    alex02    77    1
7    alex03    66    2
8    alex04    55    3

 

正向查询:

        要求: 查找user_type为CEO的有哪些人

        代码如下:

def user_info(request):
    #正向查找
    result = models.UserInfo.objects.filter(user_type__caption=CEO)
    for item in result:
        print item.username,item.age,item.user_type.caption

运行后结果如下,user_type为ceo的就一人,alex03

技术分享

 

反向查询:

通过user_type查找,UserType可用的搜索条件有:id,captin,userinfo,其中userinfo(userinfo_set)为django自动生成的对像,对应UserInfo表,我们可用于查询。

查询条件userinfo应用示例:

def user_info(request): #反向查: line = models.UserType.objects.get(id=1) print line.id print line.caption print line.userinfo_set.all()

print line.userinfo_set.filter(username=‘alex02‘)

#获取用户类型是cto有且用户名为alex02的记录

# line.userinfo_set.filter(username=‘alex02‘) 等价于==》models.UserInfo.objects.filter(user_type=line)

 

查询需求:#获取某个有是什么 用户类型?当前用户类型下有多少人?

def user_info(request):

    #获取某个有是什么 用户类型?当前用户类型下有多少人?
    user_type_obj = models.UserType.objects.get(userinfo__username=alex02)#alex02的用户类型
    print user_type_obj.caption #类型名
    print user_type_obj.userinfo_set.all().count() #这个用户类型下有多少人

执行结果:用户类型为cto的确如下2条

技术分享

 

一对多操作总结:

一对多
    1、创建
         对象(obj=model)
         _id(obj_id)
    2、查找
        正向
            查询:filter,  __跨表  对像__跨表的字段
            获取值:line.对像.跨表的字段
        反向
            查询:表名_set(filter 跨表,自动创建表名相同的对像__跨表的字段)
            获取值:line.自动创建表名相同的对像_set.filter()|all()

djanjo ORM 一对多、多对多

标签:

原文地址:http://www.cnblogs.com/tzm7614/p/5424235.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!