Django (一)

一. 基本配置

1. 数据库

DATABASES = {
    'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME':'dbname',
    'USER': 'root',
    'PASSWORD': 'xxx',
    'HOST': '',
    'PORT': '',
    }
}

# 由于Django内部连接MySQL时使用的是MySQLdb模块,而python3中还无此模块,所以需要使用pymysql来代替
  
# 如下设置放置的与project同名的配置的 __init__.py文件中
  
import pymysql
pymysql.install_as_MySQLdb()

2. 模版

TEMPLATE_DIRS = (
        os.path.join(BASE_DIR,'templates'),
    )

3. 静态文件

STATICFILES_DIRS = (
        os.path.join(BASE_DIR,'static'),
)

4. 新增APP

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app01',
    'app02',
]

二. 路由配置系统(URLconf)

URL配置(URLconf)就像Django 所支撑网站的目录。它的本质是URL与要为该URL调用的视图函数之间的映射表;你就是以这种方式告诉Django,对于这个URL调用这段代码
对于那个URL调用那段代码
    urlpatterns = [
         url(正则表达式, views视图函数,参数,别名),
]

参数说明:

    一个正则表达式字符串
    一个可调用对象,通常为一个视图函数或一个指定视图函数路径的字符串
    可选的要传递给视图函数的默认参数(字典形式)
    一个可选的name参数

1. 单一路由对应

url(r'^index$', views.index)

2. 基于正则的路由

#  $
url(r'^index/(\d{4})$',views.index)

#无命名分组
url(r'^index/(\d{4})/(\d{2})',views.index)

#有命名分组
url(r'^index/(?P<year>\d{4})/(?P<month>\d{2})',views.index)
############################无命名

#-----------------() 相当于传参数 

url(r'^index/(\d{4})',views.index)
    
    def index(request,arg):
        return HttpResponse(arg)    

#url访问http://127.0.0.1:8000/index/1113
1113

#-----------------() 接受两个参数

url(r'^index/(\d{4})/(\d{2})',views.index)

    def index(request,arg,arg1):
        return HttpResponse("year: %s month: %s"%(arg,arg1))

#url访问http://127.0.0.1:8000/index/2017/06
    year: 2017 month: 06



############################有命名
url(r'^index/(?P<year>\d{4})/(?P<month>\d{2})',views.index)

    def index(request,year,month):
        return HttpResponse("year: %s month: %s"%(year,month))

#url访问http://127.0.0.1:8000/index/2017/06
    year: 2017 month: 06
有无命名分组 演示

3. 为路由映射设置名称 

#应用一:
url(r'^index',views.index,name="arg")

{{ url "arg" }} 	匹配index
{{ url "arg" i}}

#应用二:
reverse反向获取url
##############根据url反生成名字
from django.shortcuts import reverse

url(r'^index',views.index,name="arg")

def index(request):
    v = reverse("arg")
    print(v)
    return HttpResponse()

 #用户访问http://127.0.0.1:8000/index
 /index


##############根据url改变url

url(r'^index/(\d+)/',views.index,name="n1")

def index(request,xx):

    v = reverse('n1',args=(1,))
    print(v)
    return HttpResponse("...")

 #访问http://127.0.0.1:8000/index/222/
 /index/1/
reverse示例 演示

4. 路由分发

url(r'^app01/',include("app01.urls"))
url(r'^app02/',include("app02.urls"))

#没有匹配成功,返回默认页面
url(r'^',include("views.default"))

三 .Model

a. 创建表 

from django.db import models


class User_type(models.Model):
    uid = models.BigAutoField(primary_key=True)
    title = models.CharField(max_length=32)

class User_info(models.Model):
    name = models.CharField(max_length=32)
    age = models.CharField(max_length=32)
    ut = models.ForeignKey("User_type")


python3 manage.py makemigrations

python3 manage.py migrate


---------------------其它---------------------

class part(models.Model):
    cid = models.BigAutoField(primary_key=True)
    title = models.CharField(max_length=32,null=False)


class student(models.Model):
    sid = models.BigAutoField(primary_key=True)
    name = models.CharField(max_length=32,null=False)
    pub_data=models.DateField()
    age = models.IntegerField(default=18)
    # 新增加的列 如果原先表里有值,写default
    ug = models.ForeignKey("part",null=True) #如果新增加外键,加null=True
View Code

b. ORM操作

#
# models.User_type.objects.create(title="黑金用户")
    
# obj = models.User_type(title="小白用户")
# obj.save()


#
#models.User_type.objects.filter(title="小白用户").delete()  # 删除指定条件的数据

#
#models.User_type.objects.filter(title="黑金用户").update(title="黑卡用户")    # 修改指定条件的数据

#
# models.User_type.objects.get(title="大白用户")      # 获取单条数据,不存在则报错(不建议)
# models.User_type.objects.all()                     # 获取全部
# models.User_type.objects.filter(title="小白用户")   # 获取指定条件的数据
# models.User_type.objects.exclude(title="黄金用户")     # 排除指定条件的数据
基本增删改查
# 获取个数

models.User_info.objects.filter(age=18).count()   


# 大于 小于

# models.Tb1.objects.filter(id__gt=1)               # 获取id大于1的值
# models.Tb1.objects.filter(id__gte=1)              # 获取id大于等于1的值
# models.Tb1.objects.filter(id__lt=10)              # 获取id小于10的值
# models.Tb1.objects.filter(id__lte=10)             # 获取id小于10的值
# models.Tb1.objects.filter(id__gt=1,id__lt=10)     # 获取id大于1 且 小于10的值



#in

models.User_info.objects.filter(age__in=[19])        #  in 
models.User_info.objects.exclude(age__in=[19])        #  not in


# isnull

models.User_info.objects.filter(age__isnull=True)    # age列为不为空
models.User_info.objects.filter(age__isnull=False)    # age列是不是 不为空


# contains

# models.Tb1.objects.filter(name__contains="ven")
# models.Tb1.objects.filter(name__icontains="ven")  # icontains大小写不敏感
# models.Tb1.objects.exclude(name__icontains="ven")



# range

# models.Tb1.objects.filter(id__range=[1, 5])   # 范围bettwen and


#开始 结束

# startswith,istartswith, endswith, iendswith



#order_by 

#models.User_info.objects.all().order_by("id")                # asc
#models.User_info.objects.all().order_by("-id")                # desc

# models.Tb1.objects.filter(name='seven').order_by('id')    # asc
# models.Tb1.objects.filter(name='seven').order_by('-id')   # desc



#group by     #后面出现filter代表having

from django.db.models import Count
#models.User_info.objects.values("name","age").annotate()                    #没有起作用
#SELECT "app01_user_info"."name", "app01_user_info"."age" FROM "app01_user_info"

#models.User_info.objects.values("age").annotate(xxx=Count("age"))
#SELECT "app01_user_info"."age", COUNT("app01_user_info"."age") AS "xxx" FROM "app01_user_info" GROUP BY "app01_user_info"."age"

#models.User_info.objects.values("age").annotate(xxx=Count("age")).filter(xxx__gt=2)        #年龄相同次数大于2的查出来
#SELECT "app01_user_info"."age", COUNT("app01_user_info"."age") AS "xxx" FROM "app01_user_info" GROUP BY "app01_user_info"."age" HAVING COUNT("app01_user_info"."age") > 2


#注意两次filter  第一次代表where  第二次代表having

#models.User_info.objects.filter(id__gt=2).values("age").annotate(xxx=Count("age")).filter(xxx__gt=2)        
#SELECT "app01_user_info"."age", COUNT("app01_user_info"."age") AS "xxx" FROM "app01_user_info" WHERE "app01_user_info"."id" > 2 GROUP BY "app01_user_info"."age" HAVING COUNT("app01_user_info"."age") > 2
常用方法
# F

# from django.db.models import F
# models.User_info.objects.all().update(age=F("age")+5)        # age列加5


# Q

# 方式一:
# Q(nid__gt=10)
# Q(nid=8) | Q(nid__gt=10)
# Q(Q(nid=8) | Q(nid__gt=10)) & Q(caption='root')


#-------------------------------以下三种查找方式相同效果

# obj = models.User_info.objects.filter(id=307,name="egon")

# condition ={
#     'id':307,
#     'name':'egon',
# }
# obj = models.User_info.objects.filter(**condition)

#obj = models.User_info.objects.filter(Q(id=307) & Q(name="egon"))
---------------------------------


# 方式二:


# q1 = Q()
# q1.connector = 'OR'
# q1.children.append(('id', 1))
# q1.children.append(('id', 10))
# q1.children.append(('id', 9))

# q2 = Q()
# q2.connector = 'OR'
# q2.children.append(('c1', 1))
# q2.children.append(('c1', 10))
# q2.children.append(('c1', 9))

# q3 = Q()
# q3.connector = 'AND'
# q3.children.append(('id', 1))
# q3.children.append(('id', 2))
# q1.add(q3, 'OR')

# con = Q()
# con.add(q1, 'AND')
# con.add(q2, 'AND')

#(id=1 or id=10 or id=9 or (id=1 and id=2)) and (c1=1 or c1=10 or c1=9)  #等于上面

# models.Tb1.objects.filter(con)


# Q演示
condition_dict = {
        'k1':[1,2,3,4],
        'k2':[1,],
        'k3':[11,]
}

con = Q()
for k,v in condition_dict.items():
    q = Q()
    q.connector = 'OR'
    for i in v:
        q.children.append(('id',1))
    con.add(q,'AND')

models.User_info.objects.filter(con)
F Q 演示
# extra(self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None)

# a. 映射
    select
    select_params=None
    select 此处 from# b. 条件
    where=None
    params=None
    select * from 表 where 此处

# c. 表
    table
    select * from 表,此处

# d. 排序
    prder_by=None
    select * from 表 order by 此处


result = models.User_info.objects.extra(
        select={"newid":"selet count(1) from app01_usertype where id>%s"},
        select_params=[1,],
        where = ["age>%s"],
        params=[18,],
        order_by=["-age"],
        tables=["app01_usertype"]
    )

 SELECT 
     (selet count(1) from app01_usertype where id>1) AS "newid", 
     "app01_user_info"."id", 
     "app01_user_info"."name", 
     "app01_user_info"."age", 
     "app01_user_info"."ut_id" 

 FROM "app01_user_info" , "app01_usertype" 
 WHERE (age>18) 
 ORDER BY "app01_user_info"."age" DESC



#-------------------------------------

v = models.User_info.objects.all().extra(
    select={'n':"select count(1) from app01_user_type  where uid >2"}
    )


SELECT 
    (select count(1) from app01_user_type where uid >2) AS "n", 
    "app01_user_info"."id",
    "app01_user_info"."name",
    "app01_user_info"."age", 
    "app01_user_info"."ut_id" 
FROM "app01_user_info"

#-------------------------------------

v = models.User_info.objects.all().extra(
    select={'n':"select count(1) from app01_user_type where uid=%s or uid=%s"},
    select_params=[1,3]
    )

SELECT 
    (select count(1) from app01_user_type where uid=1 or uid=3) AS "n", 
    "app01_user_info"."id", 
    "app01_user_info"."name",
    "app01_user_info"."age",
    "app01_user_info"."ut_id"
FROM "app01_user_info"

#------------- select_params ------------------------

v = models.User_info.objects.all().extra(
    select={
        'm':"select count(1) from app01_user_type where uid=%s or uid=%s",
        'n':"select count(1) from app01_user_type where uid=%s or uid=%s",
    },select_params=[1,2,3,4])


SELECT 
    (select count(1) from app01_user_type where uid=1 or uid=2) AS "m",
    (select count(1) from app01_user_type where uid=3 or uid=4) AS "n",
    "app01_user_info"."id", 
    "app01_user_info"."name", 
    "app01_user_info"."age", 
    "app01_user_info"."ut_id" 
FROM "app01_user_info"



#--------------  where  -----------------------

v = models.User_info.objects.extra(
    where=["id=%s or id=%s","name=%s"],
    params=[1,307,"egon"]
)


SELECT 
    "app01_user_info"."id",
    "app01_user_info"."name",
    "app01_user_info"."age",
    "app01_user_info"."ut_id"
FROM "app01_user_info" WHERE (id=1 or id=307) AND (name=egon)


#--------------  table  -----------------------

#笛卡尔积

#示例一:
result = models.User_info.objects.extra(
    tables=["app01_user_type"],
)


SELECT 
    "app01_user_info"."id", 
    "app01_user_info"."name", 
    "app01_user_info"."age", 
    "app01_user_info"."ut_id" 

FROM "app01_user_info" , "app01_user_type"


#示例二:


result = models.User_info.objects.extra(
    tables=["app01_user_type"],
    where=["app01_usertype.id = app01_userinfo.ut_id"]
)


SELECT 
    "app01_user_info"."id", 
    "app01_user_info"."name", 
    "app01_user_info"."age", 
    "app01_user_info"."ut_id" 

FROM "app01_user_info" , "app01_user_type" 
WHERE (app01_usertype.id = app01_userinfo.ut_id)
extra
# 获取到querySet里面的结果如果是对象 循环对象. 实现跨表
                    结果如果是{}或(),取值时__实现跨表


models.UserInfo.object.all()                            #获取到querySet 里面是对象类型    [obj,obj,obj]
                                                        #对象可以分装很多值,可以跨表

models.UserInfo.object.all().values("id","name")        #获取到querySet 里面是字典类型    [{},{},{},{}]
                                                        #obj["id"],obj["name"]

models.UserInfo.object.all().values_list("id","name")   #获取到querySet 里面是元组类型 [(),(),()]
                                                        #obj[0],obj[1]

models.UserInfo.object.all().values("id","name","ut__title")
对象 字典 列表

c. 多对多操作

方式一:通过外键创建第三张表

m = models.ManyToManyField("Girl")   	#如果下面写成这种方式会创建4张表
m = models.ManyToManyField("Girl",through="Love",through_fields=("b","g",))		#会生成3张表

ManyToManyField


class Boy(models.Model):
    name = models.CharField(max_length=32)
   
 
class Girl(models.Model):
    nick = models.CharField(max_length=32)
 
class Love(models.Model):
    b = models.ForeignKey("Boy")
    g = models.ForeignKey("Girl")
 
    class Meta:
        unique_together = [
            ("b","g"),
        ]
#表里插入数据

objs = [
        models.Boy(name='方少伟'),
        models.Boy(name='游勤斌'),
        models.Boy(name='于浩'),
        models.Boy(name='陈涛'),
]
models.Boy.objects.bulk_create(objs,4)

result = [
    models.Girl(nick='于浩姐姐'),
    models.Girl(nick='景甜'),
    models.Girl(nick='刘亦非'),
    models.Girl(nick='苍老师'),
]
models.Girl.objects.bulk_create(result, 4)

models.Love.objects.create(b_id=1,g_id=1)
models.Love.objects.create(b_id=1,g_id=2)
models.Love.objects.create(b_id=1,g_id=3)
models.Love.objects.create(b_id=2,g_id=4)


###################   查找和我有关系的女孩  四种方式 ################


obj = models.Boy.objects.filter(name="方少伟").first()
love_list = obj.love_set.all()
for row in love_list:
   print(row.g.nick)

love_list = models.Love.objects.filter(b__name="方少伟")
for row in love_list:
    print(row.g.nick)


#下面两个效果好

love_list = models.Love.objects.filter(b__name="方少伟").values("g__nick")
for item in love_list:
    print(item["g__nick"])   
    


love_list = models.Love.objects.filter(b__name="方少伟").select_related("g")
for obj in love_list:
    print(obj.g.nick)
SQL演示

方式二:通过 ManyToManyField 创建第三张表

class Boy(models.Model):
    name = models.CharField(max_length=32)
    m = models.ManyToManyField("Girl")

class Girl(models.Model):
    nick = models.CharField(max_length=32)
obj = models.Boy.objects.filter(name="方少伟").first()
    # print(obj.id,obj.name)

    # obj.m.add(2)
    # obj.m.add(1,3)
    # obj.m.add(*[4,])

    # obj.m.remove(2)
    # obj.m.remove(1,3)
    # obj.m.remove(*[4,])

    # obj.m.set([1,4,])


    # girl_list = obj.m.all()
    # girl_list = obj.m.filter(nick="苍老师")


    # obj.m.clear()

obj = models.Girl.objects.filter(nick="苍老师").first()
v = obj.boy_set.all()        
SQL 演示

方式三:通过 外键 和 ManyToManyField 创建

class Boy(models.Model):
    name = models.CharField(max_length=32)
    m = models.ManyToManyField("Girl",through="Love",through_fields=("b","g",))

class Girl(models.Model):
    nick = models.CharField(max_length=32)

class Love(models.Model):
    b = models.ForeignKey("Boy")
    g = models.ForeignKey("Girl")

    class Meta:
        unique_together = [
            ("b","g"),
        ]
obj = models.Boy.objects.filter(name="方少伟").first()

#只可以查或清空
obj.m.clear()

obj.m.all()
SQL 操作

d. 一对多 

# 对象连表正向操作:
 
objSet = models.User_info.objects.all()
for obj in objSet:
    print(obj.name, obj.age, obj.ut.title)
 
 
# 对象连表反向操作:
 
objSet = models.User_type.objects.all()
for row in objSet:
    print(row.title, row.user_info_set.all())
    for i in row.user_info_set.all():
        print(i.name)
 
# value连表正向操作:
 
obj = models.User_info.objects.values("ut__title","name")
for row in obj:
    print(row)
 
# value连表反向操作:
 
obj = models.User_type.objects.values("user_info__name","title")
for row in obj:
    print(row)
View Code

1.连表操作演示

urlpatterns = [
 
    url(r'^test/', views.test),

]
urls.py
class User_type(models.Model):
    uid = models.BigAutoField(primary_key=True)
    title = models.CharField(max_length=32)

class User_info(models.Model):
    name = models.CharField(max_length=32)
    age = models.CharField(max_length=32)
    ut = models.ForeignKey("User_type")
models.py
def test(request):
    models.User_type.objects.create(title="普通用户")
    models.User_type.objects.create(title="白金用户")
    models.User_type.objects.create(title="黄金用户")


    models.User_info.objects.create(name="小鸡",age=18,ut_id=1)
    models.User_info.objects.create(name="小狗",age=18,ut_id=2)
    models.User_info.objects.create(name="小猫",age=18,ut_id=2)
    models.User_info.objects.create(name="小雨",age=18,ut_id=3)
    models.User_info.objects.create(name="大雨",age=18,ut_id=1)

    for i  in range(300):
        name = "root" + str(i)
        models.User_info.objects.create(name=name, age=18, ut_id=1)

    #正向操作
    obj = models.User_info.objects.all().first()
    print(obj.name,obj.age,obj.ut.title)

    #反向操作   obj.表名小写_set.all()
    obj = models.User_type.objects.all().first()
    for row in obj.user_info_set.all():
        print(row.name,row.age)

    result = models.User_type.objects.all()
    for item in result:
        print(item.title,item.user_info_set.all())
        print(item.user_info_set.filter(name="小雨"))


    #字典格式
    result = models.User_info.objects.all().values("id","name")
    for row in result:
        print(row)

    #字典格式查的时候跨表
    result = models.User_info.objects.all().values("id","name","ut__title")
    for row in result:
        print(row["id"],row["name"],row["ut__title"])





    # 元组格式
    # result = models.User_info.objects.all().values_list("id","name")
    # for row in result:
    #     print(row)

    return HttpResponse(".....")
views.py

e. 关联

1. 方式一:

class UserInfo(models.Model):
    nickname = models.CharField(max_length=32)
    username = models.CharField(max_length=32)
    password = models.CharField(max_length=64)
    gender_choices = (
        (1,''),
        (2,''),
    )
    gender = models.IntegerField(choices=gender_choices)


# obj对象男.a.all()     反向查找
# obj对象女.b.all()     反向查找
class U2U(models.Model):
    b = models.ForeignKey("UserInfo",related_name="a")
    g = models.ForeignKey("UserInfo",related_name="b")


# obj对象男.a_set.all()     反向查找
# obj对象女.b_set.all()     反向查找
# class U2U(models.Model):
#     b = models.ForeignKey("UserInfo",related_query_name="a")
#     g = models.ForeignKey("UserInfo",related_query_name="b")
ForeignKey 关联两个表
    # models.U2U.objects.create(b_id=2,g_id=5)
    # models.U2U.objects.create(b_id=2,g_id=4)
    # models.U2U.objects.create(b_id=2,g_id=6)

    #这种方式也是插入的ID
    # boy = models.UserInfo.objects.filter(gender=1,id=2).first()
    # girl = models.UserInfo.objects.filter(gender=2,id=5).first()
    # models.U2U.objects.create(b_id=boy,g_id=girl)
插入性别两种方式
    two = models.UserInfo.objects.filter(id=2).first()
    result = two.girls.all()
    for u in result:
        print(u.g.nickname)
查找数据

2. 方式二:

class UserInfo(models.Model):
    nickname = models.CharField(max_length=32)
    username = models.CharField(max_length=32)
    password = models.CharField(max_length=64)
    gender_choices = (
        (1,''),
        (2,''),
    )
    gender = models.IntegerField(choices=gender_choices)
    m = models.ManyToManyField("UserInfo")



#--------------------------------------------


    #   男生查女生
    #   xz.m 用的第二张表的第一列
    xz = models.UserInfo.objects.filter(id=1).first()
    u = xz.m.all()
    for row in u:
        print(row.nickname)


    #   女生查男生
    #   xz.userinfo_set 用的第二张表的第二列
    xz =  models.UserInfo.objects.filter(id=4).first()
    v = xz.userinfo_set.all()
    for row in v:
        print(row.nickname)
View Code

f: 例子

from django.db import models


class UserInfo(models.Model):
    """
    用户表
    """
    nid = models.BigAutoField(primary_key=True)
    username = models.CharField(verbose_name='用户名', max_length=32, unique=True)
    password = models.CharField(verbose_name='密码', max_length=64)
    nickname = models.CharField(verbose_name='昵称', max_length=32)
    email = models.EmailField(verbose_name='邮箱', unique=True)
    avatar = models.ImageField(verbose_name='头像')

    create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)

    fans = models.ManyToManyField(verbose_name='粉丝们',
                                  to='UserInfo',
                                  through='UserFans',
                                  related_name='f',
                                  through_fields=('user', 'follower'))


class Blog(models.Model):
    """
    博客信息
    """
    nid = models.BigAutoField(primary_key=True)
    title = models.CharField(verbose_name='个人博客标题', max_length=64)
    site = models.CharField(verbose_name='个人博客前缀', max_length=32, unique=True)
    theme = models.CharField(verbose_name='博客主题', max_length=32)
    user = models.OneToOneField(to='UserInfo', to_field='nid')


class UserFans(models.Model):
    """
    互粉关系表
    """
    user = models.ForeignKey(verbose_name='博主', to='UserInfo', to_field='nid', related_name='users')
    follower = models.ForeignKey(verbose_name='粉丝', to='UserInfo', to_field='nid', related_name='followers')

    class Meta:
        unique_together = [
            ('user', 'follower'),
        ]


class Category(models.Model):
    """
    博主个人文章分类表
    """
    nid = models.AutoField(primary_key=True)
    title = models.CharField(verbose_name='分类标题', max_length=32)

    blog = models.ForeignKey(verbose_name='所属博客', to='Blog', to_field='nid')


class ArticleDetail(models.Model):
    """
    文章详细表
    """
    content = models.TextField(verbose_name='文章内容', )

    article = models.OneToOneField(verbose_name='所属文章', to='Article', to_field='nid')


class UpDown(models.Model):
    """
    文章顶或踩
    """
    article = models.ForeignKey(verbose_name='文章', to='Article', to_field='nid')
    user = models.ForeignKey(verbose_name='赞或踩用户', to='UserInfo', to_field='nid')
    up = models.BooleanField(verbose_name='是否赞')

    class Meta:
        unique_together = [
            ('article', 'user'),
        ]


class Comment(models.Model):
    """
    评论表
    """
    nid = models.BigAutoField(primary_key=True)
    content = models.CharField(verbose_name='评论内容', max_length=255)
    create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)

    reply = models.ForeignKey(verbose_name='回复评论', to='self', related_name='back', null=True)
    article = models.ForeignKey(verbose_name='评论文章', to='Article', to_field='nid')
    user = models.ForeignKey(verbose_name='评论者', to='UserInfo', to_field='nid')


class Tag(models.Model):
    nid = models.AutoField(primary_key=True)
    title = models.CharField(verbose_name='标签名称', max_length=32)
    blog = models.ForeignKey(verbose_name='所属博客', to='Blog', to_field='nid')


class Article(models.Model):
    nid = models.BigAutoField(primary_key=True)
    title = models.CharField(verbose_name='文章标题', max_length=128)
    summary = models.CharField(verbose_name='文章简介', max_length=255)
    read_count = models.IntegerField(default=0)
    comment_count = models.IntegerField(default=0)
    up_count = models.IntegerField(default=0)
    down_count = models.IntegerField(default=0)
    create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)

    blog = models.ForeignKey(verbose_name='所属博客', to='Blog', to_field='nid')
    category = models.ForeignKey(verbose_name='文章类型', to='Category', to_field='nid', null=True)

    type_choices = [
        (1, "Python"),
        (2, "Linux"),
        (3, "OpenStack"),
        (4, "GoLang"),
    ]

    article_type_id = models.IntegerField(choices=type_choices, default=None)

    tags = models.ManyToManyField(
        to="Tag",
        through='Article2Tag',
        through_fields=('article', 'tag'),
    )


class Article2Tag(models.Model):
    article = models.ForeignKey(verbose_name='文章', to="Article", to_field='nid')
    tag = models.ForeignKey(verbose_name='标签', to="Tag", to_field='nid')

    class Meta:
        unique_together = [
            ('article', 'tag'),
        ]
sql.py
    #一对多  获取当前博客所有文章

    #正向
    models.Article.objects.filter(blog=blog)
    models.Article.objects.filter(blog_id=blog.nid)
    #反向
    blog = models.Blog.objects.filter(site=site).first()
    blog.article_set.all()


    # 一对一 将blog和userinfo连接在一起,再根据site进行筛选

    # 正向 通过博客,获取用户信息:
    blog = models.Blog.objects.filter(site=site).first()
    print(blog.user.nickname)

    models.Blog.objects.filter(site=site).values('site','user__nickname')
    
    #反向
    v = models.UserInfo.objects.filter(blog__site=site).values('blog__site','nickname')
    
    obj = models.Blog.objects.filter(site=site).first()
    print(obj.user.nickname)

    #反向 给用户名,获取博客后缀
    obj = models.UserInfo.objects.filter(username='sw').first()
    print(obj.blog.site)

  

 

--------------------------------------------------------------
all()                        [obj,obj,obj]
filter()                     [obj,obj,obj]
first()                      obj
values("uid","title")        [{},{},{}]
value_list()                 [(),(),()]

    models.user_info.objects.values("uid","title")         
            [ {"uid":1,"title":"CEO"},{"uid":2,"title":"CTO"},{"uid":3,"title":"CFO"}  
    models.User_type.objects.values_list("uid","title")
        [(1, 'CEO'), (2, 'CFO')]                           


---------------------------------------------------------------

一对多:

    class User_type(models.Model):
    uid = models.BigAutoField(primary_key=True)
    title = models.CharField(max_length=32)


    class User_info(models.Model):
        name = models.CharField(max_length=32)
        age = models.CharField(max_length=32)
        ut = models.ForeignKey("User_type")


    User_type               User_info

    id   title              id   name    age     ut
    1      CTO              1     alex    18      1
                            2     egon    17      1


    1. 正向操作    
        
        #对象查找   跨表 对象.关联字段.字段

            user_obj = models.User_info.objects.filter(id=1).first()

            print("user_obj.id---",user_obj.id)
            print("user_obj.name---", user_obj.name)
            print("user_obj.age---", user_obj.age)
            print("user_obj.ut---", user_obj.ut)
            print("user_obj.ut_id---", user_obj.ut_id)
            print("user_obj.ut.uid---", user_obj.ut.uid)
            print("user_obj.ut.title---", user_obj.ut.title)

        #字段查找   跨表  关联字段__字段

            models.User_info.objects.values("id","name","ut_id","ut__uid","ut__title")

    2. 反向操作

        #对象查找       跨表 对象.小写表名_set().all()  循环对象.字段

            type_obj = models.User_type.objects.filter(uid=1).first()

            print("type_obj.id---",type_obj.uid)
            print("type_obj.title---", type_obj.title)
            print("obj", type_obj.user_info_set.all())
            
            obj = type_obj.user_info_set.all()
            for i in obj:
                print(i.id)
                print(i.name)
                print(i.ut_id)


        #字段查找  跨表   反向小写表名__字段     

            models.User_type.objects.values("uid","title","user_info__name","user_info__age")
一对多跨表操作

 

 

 

 http://www.cnblogs.com/wupeiqi/articles/6216618.html

  

  

 

  

  

吴沛齐  

  

 

 

posted @ 2017-06-22 14:16  golangav  阅读(849)  评论(0编辑  收藏  举报