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

Django进阶2

时间:2016-06-17 12:42:37      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:

一、ORM操作进阶

ForeignKey关联

示例models

from django.db import models
# Create your models here.
class User(models.Model):
    name = models.CharField(max_length=32)

class Host(models.Model):
    host_name = models.CharField(max_length=32)
    blong_to = models.ForeignKey("User")

ForeignKey创建数据

models.Host.objects.create(host_name="127.0.0.1",blong_to=models.User.objects.get(id=1))

1、搜索条件使用 __ 连接  2、获取值时使用 . 连接

user_list=models.Host.objects.filter(blong_to__name="lisi")    #一对多过滤条件

for item in user_list:
    print(item.host_name,item.blong_to.name)  #取数据,在前端取数据也类似

 

ForeignKey修改数据

hosts=models.Host.objects.get(host_name="127.0.0.1")
users=models.User.objects.get(id=2)

hosts.blong_to=users
hosts.save()

反向关联查询

user_obj=models.User.objects.get(id=2)
print(user_obj.host_set.select_related())

 

ManyToManyField关联

示例models

class UserInfo(models.Model):
    name = models.CharField(max_length=32)
    email = models.CharField(max_length=32)
    address = models.CharField(max_length=128)


class UserGroup(models.Model):
    caption = models.CharField(max_length=64)
    user_info = models.ManyToManyField(UserInfo)

 

ManyToManyField操作(_set是多对多中的固定搭配)

    user_info_obj = models.UserInfo.objects.get(name="zhangsan")
    user_info_objs = models.UserInfo.objects.all()

    group_obj = models.UserGroup.objects.get(caption=CEO)
    group_objs = models.UserGroup.objects.all()

    # 添加数据
    #group_obj.user_info.add(user_info_obj)
    #group_obj.user_info.add(*user_info_objs)
    #
    #user_info_obj.usergroup_set.add(group_obj)
    #user_info_obj.usergroup_set.add(*group_objs)

    # 删除数据
    #group_obj.user_info.remove(user_info_obj)
    #group_obj.user_info.remove(*user_info_objs)
    #
    #user_info_obj.usergroup_set.remove(group_obj)
    #user_info_obj.usergroup_set.remove(*group_objs)

    # 获取数据
    #print group_obj.user_info.all()
    #print group_obj.user_info.all().filter(id=1)
    #
    #print user_info_obj.usergroup_set.all()
    #print user_info_obj.usergroup_set.all().filter(caption=‘CEO‘)

 

 F  对同一表内不同的字段进行对比查询

class Entry(models.Model):
    n_comments = models.IntegerField()
    n_pingbacks = models.IntegerField()
    rating = models.IntegerField()
from django.db.models import F
models.Entry.objects.filter(n_comments__gt=F(n_pingbacks))
models.Entry.objects.filter(n_comments__gt=F(n_pingbacks) * 2)
models.Entry.objects.filter(rating__lt=F(n_comments) + F(n_pingbacks))

批量自增

models.Entry.objects.all().update(n_pingbacks=F(n_pingbacks) + 1)

 

Q  构建搜索条件

from django.db.models import Q

models.UserInfo.objects.get(
    Q(name=zhangsan),Q(email="12345678@qq.com"))  #两个都要满足
models.UserInfo.objects.get(
    Q(name=zhangsan) | Q(email="12345678@qq.com"))  #只需满足一个
models.UserInfo.objects.get(
    Q(name=zhangsan),Q(email="12345678@qq.com") | Q(address="abcde"))

 

django 实现分页

实例

技术分享
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from django.shortcuts import render,HttpResponse
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from app01 import models
# Create your views here.
def stu_login(request):
    return render(request,"app01/login.html")


def stu_home(request):
    customer_list=models.Customer.objects.all()
    paginator = Paginator(customer_list, 1) #每页显示条数

    page = request.GET.get(page)
    try:
        contacts = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        contacts = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        contacts = paginator.page(paginator.num_pages)

    return render(request, "app01/home.html", {"customer_list":contacts})
views
技术分享
    <div class="pagination">
        <nav>
            <ul class="pagination">
                {% if customer_list.has_previous %}
                    <li class=""><a href="?page={{ customer_list.previous_page_number }}" aria-label="Previous"><span aria-hidden="true">&laquo;</span></a></li>
                {% endif %}
                {% for page_num in customer_list.paginator.page_range %}
                    {% if page_num == customer_list.number %}<!--如果page_num是当前选中的页-->
                      <li class="active"><a href="?page={{ page_num }}">{{ page_num }} <span class="sr-only">(current)</span></a></li>
                    {% else %}
                      <li class=""><a href="?page={{ page_num }}">{{ page_num }} <span class="sr-only">(current)</span></a></li>
                    {% endif %}
                {% endfor %}
                {% if customer_list.has_next %}
                    <li class=""><a href="?page={{ customer_list.next_page_number }}" aria-label="Next"><span aria-hidden="true">&raquo;</span></a></li>
                {% endif %}
            </ul>
        </nav>
    </div>
html

 

优化:固定页码个数

1、自定义template tags

  技术分享

技术分享
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from django import template
from django.utils.safestring import mark_safe

register = template.Library()

@register.simple_tag
def custemer_paging(current_page,loop_num): #传入选中页和循环页
    num_left=current_page-2
    num_right=current_page+2
    if loop_num>num_left and loop_num<num_right:#只显示3页
        if current_page == loop_num:
            result=‘‘‘<li class="active"><a href="?page=%s">%s <span class="sr-only">(current)</span></a></li>‘‘‘%(loop_num,loop_num)
        else:
            result=‘‘‘<li class=""><a href="?page=%s">%s <span class="sr-only">(current)</span></a></li>‘‘‘%(loop_num,loop_num)
        return mark_safe(result)
    result=""
    return mark_safe(result)
custemer_tags.py

 

在html开头导入

{% load custemer_tags %}

 

使用自定义simple_tag

技术分享
    <div class="pagination">
        <nav>
            <ul class="pagination">
                {% if customer_list.has_previous %}
                    <li class=""><a href="?page={{ customer_list.previous_page_number }}" aria-label="Previous"><span aria-hidden="true">&laquo;</span></a></li>
                {% endif %}
                {% for page_num in customer_list.paginator.page_range %}
                    
                    {% custemer_paging customer_list.number page_num %}<!--使用custemer_tags-->

                {% endfor %}
                {% if customer_list.has_next %}
                    <li class=""><a href="?page={{ customer_list.next_page_number }}" aria-label="Next"><span aria-hidden="true">&raquo;</span></a></li>
                {% endif %}
            </ul>
        </nav>
    </div>
View Code

 

更多详情:https://docs.djangoproject.com/en/1.9/topics/pagination/ 

 

三、在自己写的脚本里调用django models

技术分享
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
os.environ[DJANGO_SETTINGS_MODULE] = django_project.settings
import django
django.setup()

from app01 import models

result = models.UserInfo.objects.get(id=1)
print(result)
View Code

技术分享

 

四、用户认证

from django.contrib.auth.models import User

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    name = models.CharField(max_length=32)

 

from django.contrib.auth import authenticate,login,logout
from django.contrib.auth.decorators import login_required

@login_required
def acc_home(request):
    return render(request,"index.html")

def acc_login(request):
    if request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        user = authenticate(username=username,password=password) #验证

        if user is not None:
            login(request,user) #登录
            return redirect("/app01/acc_home/")
    else:
        return render(request,"login.html")

def acc_logout(request):
    logout(request) #退出

在前端显示用户名或对应的名字

    <div>
        {% if request.user.is_authenticated %} <!--如果已经登录-->
            <span>{{ request.user }}</span> <!--用户名-->
            <span>{{ request.user.userprofile.name }}</span> <!--用户名在UserProfile表对应的名字-->
        {% endif %}
    </div>

 

Django进阶2

标签:

原文地址:http://www.cnblogs.com/melonjiang/p/5565799.html

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