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

BBS - 首页、个人站点、ORM

时间:2018-06-04 19:12:56      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:default   int   color   分组   play   any   根目录   order   foreign   

技术分享图片
1 ajax和用户认证组件
      ----PIL和session

2 ajax和form组件注册功能

  (1) form请求和ajax上传文件
      form请求:
             <form action="" novalidate enctype="multipart/form-data">
             </form>

             request.FILES("avatar")

      ajax:
            formdata=new FormData()
            formdata.append("","")
            $.ajax({
                url:""
                processData:false,
                contentType:false
                data:formdata
            })

            request.FILES("avatar")

  (2)图像预览

  (3)form组件:
        class Userform(forms.Form):
             user=forms.Charfield()
             email=forms.Emailfield()

        def reg():
            if request.method=="GET":
               form=Userform()
               return render(request,"reg.html",locals())
        在reg.html:
            渲染方式:
               1 :{{form.as_p}}
               2 : {{form.user}}  {{form.user.label}}
               3 : {%for field in form%}
                     {{field}}  {{field.label}}
                   {%endfor%}

        def reg():
            if request.method=="POST":
               form=Userform(request.POST)
               if form.is_valid():
                   form.cleaned_data

               else:
                   form.errors

               return ......

  (4) media配置:
        静态文件的处理又包括STATIC和MEDIA两类,这往往容易混淆,在Django里面是这样定义的:

        MEDIA: 指用户上传的文件,比如在Model里面的FileFIeld,ImageField上传的文件。
        STATIC:指服务器自己的文件。


        示例:
            class User():
                avatar = models.FileField(upload_to=avatars/, default="/avatars/default.png")


            if 实例化一个User对象的时候,avatar字段会接收一个文件对象,这个文件对象
            会默认保存到项目的根目录对应的upload_to=avatars/的位置

        配置1:
            MEDIA_ROOT=os.path.join(BASE_DIR,"blog","media")

            if 实例化一个User对象的时候,avatar字段会接收一个文件对象,这个文件对象
            会默认保存到MEDIA_ROOT对应路径的upload_to=avatars/的位置

        配置2:
            settings:
                MEDIA_URL="/media/"
            url.py:
                from django.views.static import serve
                from cnblog_s9 import settings
                # media 配置
                url(r^media/(?P<path>.*)$, serve, {document_root: settings.MEDIA_ROOT}),


            http://127.0.0.1:8000/media/avatars/lufei.jpg


博客系统:
    系统首页
    admin:数据库后台管理web页面

    个人站点:

    查询

        基于对象查询(子查询)

        基于queryset查询(join查询)
笔记

一、首页

二、admin

三、个人站点

四、ORM查询练习

models.py

from django.db import models

class AuthorDetail(models.Model):
    nid = models.AutoField(primary_key=True)
    birthday = models.DateField()
    telephone = models.BigIntegerField()
    addr = models.CharField(max_length=64)

class Author(models.Model):
    nid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    age = models.IntegerField()
    # 与AuthorDetail建立一对一的关系
    authorDetail = models.OneToOneField(to="AuthorDetail",on_delete=models.CASCADE,related_name=authors)

class Publish(models.Model):
    nid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    city = models.CharField(max_length=32)
    email = models.EmailField()


class Book(models.Model):
    nid = models.AutoField(primary_key=True)
    title = models.CharField(max_length=32)
    publishDate = models.DateField()
    price = models.DecimalField(max_digits=5, decimal_places=2)
    keepNum = models.IntegerField()
    commentNum = models.IntegerField()

    # 与Publish建立一对多的关系,外键字段建立在多的一方
    publish = models.ForeignKey(to="Publish", to_field="nid",on_delete=models.CASCADE)

    # 与Author表建立多对多的关系,ManyToManyField可以建在两个模型中的任意一个,自动创建第三张表
    authors = models.ManyToManyField(to=Author)

 技术分享图片

 

orm查询 

基于对象 、 基于queryset 和 __ 、 分组

from django.shortcuts import render,HttpResponse

from app01.models import *

def query(request):

    ###################### 基于对象得跨表查询 (子查询)######################
    """
    一对多: Book  -------> Publish
            正向查询按字段   反向查询按表名 小写_set
    """


    # 1.查询 id=2 得书籍对应得出版社得邮箱  正向
    ret = Book.objects.filter(nid=2).first().publish.email

    # 2.橘子出版社出版过得所有书籍得名字    反向
    ret = Publish.objects.filter(name=橘子出版社).first().book_set.all().values(title)


    """
    多对多: Book  -------> Author
            正向查询按字段   反向查询按表名 小写_set
    """
    # 1. 查询金瓶mei所有作者得名字   正向
    ret = Book.objects.filter(title=金瓶mei).first().authors.all().values(name)

    # 2.作者alex 出版过得书籍得个数  反向
    ret = Author.objects.filter(name=alex).first().book_set.all().values(title)
    ret = Author.objects.filter(name=alex).first().book_set.all().count()


    """
    一对一: Author  -------> AuthorDetail
            正向查询按字段   反向查询按表名 小写  或者自定义得 related_name=‘authors‘
    """
    # 1.查询alex得手机号   正向
    ret = Author.objects.filter(name=alex).first().authorDetail.telephone

    # 2.住在烟台得作者得名字  反向
    ret = AuthorDetail.objects.filter(addr=烟台).first().authors.name
    ret = AuthorDetail.objects.filter(addr=烟台)
    for i in ret:
        print(i.authors.name)


    ###########################################
    # 基于对象得跨表查询 (子查询)

    """
       SELECT 
         "app01_book"."nid", 
         "app01_book"."title", 
         "app01_book"."publishDate", 
         "app01_book"."price",
         "app01_book"."publish_id" 
     FROM "app01_book"
        WHERE 
         "app01_book"."nid" = 1 
        ORDER BY 
         "app01_book"."nid" ASC LIMIT 1; args=(1,)

    SELECT 
       "app01_publish"."nid",
       "app01_publish"."name", 
       "app01_publish"."city",
       "app01_publish"."email" 
     FROM "app01_publish" 
     WHERE 
     "app01_publish"."nid" = 1; args=(1,)

    """


    ###################### 基于queryset和__ 得跨表查询 ######################

    """
    正向查询按字段 反向查询按表名
    """
    # 1.查询 价格为100 得书籍对应得出版社得邮箱
    ret = Book.objects.filter(price=100).values(publish__email)
    """
    values:内部
    queryset = Book.objects.filter(price=100)
    temp = []
    for obj in queryset:
        temp.append({
            ‘title‘:obj.title,
            ‘publish_email‘:obj.publish_email
        })
    temp
    """

    # 2.橘子出版社出版过得所有书籍得名字
    ret = Publish.objects.filter(name=橘子出版社).values("book__title")
    ret = Book.objects.filter(publish__name=橘子出版社).values(title)

    # 1. 查询金瓶mei所有作者得名字
    ret = Book.objects.filter(title=金瓶mei).values(authors__name)
    ret = Author.objects.filter(book__title=金瓶mei).values(name)

    # 2.作者alex 出版过得书籍得个数
    ret = Author.objects.filter(name=alex).values(book__title).count()
    ret = Book.objects.filter(authors__name=alex).values(title).count()

    # 1.查询alex得手机号
    ret = Author.objects.filter(name=alex).values(authorDetail__telephone)
    ret = AuthorDetail.objects.filter(authors__name=alex).values(telephone)

    # 2.住在烟台得作者得名字
    ret = Author.objects.filter(authorDetail__addr=烟台).values(name)
    ret = AuthorDetail.objects.filter(addr=烟台).values(authors__name)


    ###########################################
    # 基于queryset和__ 得跨表查询

    """
        SELECT 
          "app01_book"."title", 
          "app01_book"."price" 
        FROM 
          "app01_book" 
        INNER JOIN "app01_publish" ON 
          ("app01_book"."publish_id" = "app01_publish"."nid")
        WHERE 
          "app01_publish"."name" = ‘人名出版社2‘ LIMIT 21; args=(‘人名出版社2‘,)
    
    """


    ###################### 分组查询(annotate) 与 聚合查询(avg count sum min)######################
    # 员工表 emp  部门表 dep
    """
    单表分组
        sql:
            select dep,AVG(salary) from emp group by dep
        
        ORM查询
            Emp.objects.values(‘dep‘).annotate(dep_avg = AVG(salary)).values(‘dep‘,‘dep_avg‘)
            
    多表分组
        sql:
            select AVG(salary) from emp group by dep_id
            
            select dep.name,AVG(emp.salary) from emp inner join dep on (emp.dep_id == dep.id) group by emp.dep_id
                        
        ORM查询:
            ...
            ...
               
    """

    # 1.每个出版社出版过得书名称,书得个数
    from django.db.models import Count,Avg

    # ret = Publish.objects.all().annotate() # 每个出版社对象 被分为一个组
    # select * from publish group by id

    ret = Publish.objects.all().annotate(book_count = Count(book__title)).values(name,book_count)

    # 2.每一个作者名字以及对应书籍得平均价格
    ret = Author.objects.all().annotate(books_avg = Avg(book__price)).values(name,books_avg)

    # 3.查询每一本书得名字以及作者得个数
    ret = Book.objects.all().annotate(authors_count = Count(authors)).values(title,authors_count)


    # 单表分组查询?
    Book.objects.all().annotate()  # 每一个book 得 id group by

    # select 哪个字段 就按 哪个字段 group by
    ret = Book.objects.all().values(title).annotate(c = Count(*)).values(title,c)
    #  SELECT "app01_book"."title", COUNT(*) AS "c" FROM "app01_book" GROUP BY "app01_book"."title"; args=()


    ###########################################

    # from django.core import serializers    # 将quertset转化成json
    # ret = serializers.serialize(‘json‘,ret)
    # return HttpResponse(ret)

    # import json
    # return HttpResponse(json.dumps(list(ret),ensure_ascii=False))

    print(ret)
    return HttpResponse(ret)

 

BBS - 首页、个人站点、ORM

标签:default   int   color   分组   play   any   根目录   order   foreign   

原文地址:https://www.cnblogs.com/alice-bj/p/9134800.html

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