zoukankan      html  css  js  c++  java
  • python 项目随笔-2

    python版本 3.6.1

    django 1.10.1

    http://www.zmrenwu.com/category/django-blog-tutorial/


    1.mysql数据库 设置
    安装 pip install pymysql
    安装 pip install mysqlclient
    设置 mysql连接的参数
    settings.py
    DATABASES = {

    'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': "py3django",
    'USER': "root",
    'PASSWORD': "123456",
    'HOST': "127.0.0.1",
    }
    }
    2 常用指令
    启动服务 runserver
    迁移数据库
    makemigrations
    migrate
    创建用户 createsuperuser
    根据提示 输入用户,输入邮箱,输入密码
    进入shell界面 :shell

    3.models.py 的操作
    https://docs.djangoproject.com/en/1.10/ref/models/querysets/
    获取所有数据 类对象.objects.all()
    获取过滤的数据,进返回一条数据,get方法
    类对象.objects.get(name='category test')
    Category.objects.get(name='category test') 的含义是从数据库中取出 name 的值为 category test 的分类记录。
    确保数据库中只有一条值为 category test 的记录,否则 get 方法将返回一个 MultipleObjectsReturned 异常。
    保存数据, xx=类对象.objects.all()
    xx.save() #增 改
    xx.delete() #删除
    https://docs.djangoproject.com/en/1.10/ref/models/querysets/
    QuerySet

    4.models类对象数据显示优化
    为了让显示出来的数据更加人性化一点,为模型分别增加一个 __str__ 方法:
    def __str__(self):
    return self.name
    定义好 __str__ 方法后,解释器显示的内容将会是 __str__ 方法返回的内容。

    注意:python_2_unicode_compatible 装饰器用于兼容 Python2
    (from django.utils.six import python_2_unicode_compatible)
    # python_2_unicode_compatible 装饰器用于兼容 Python2
    @python_2_unicode_compatible
    class Category(models.Model):
    ...

    def __str__(self):
    return self.name

    5.查询 QuerySet API
    https://docs.djangoproject.com/en/1.10/ref/models/querysets/
    filter(**kwargs) :返回包含所有符合条件的 QuerySet,对应的参数,须为查询的表中的字段
    Returns a new QuerySet containing objects that match the given lookup parameters.
    The lookup parameters (**kwargs) should be in the format described in Field lookups below.
         Multiple parameters are joined via AND in the underlying SQL statement.
    exclude(**kwargs) :过滤条件 不包括(即 not in )
    This example excludes all entries whose pub_date is later than 2005-1-3 AND whose headline is “Hello”:
    Entry.objects.exclude(pub_date__gt=datetime.date(2005, 1, 3), headline='Hello')
    SQL语句:SELECT ...
    WHERE NOT (pub_date > '2005-1-3' AND headline = 'Hello')
    或者
    SELECT ...
    WHERE NOT pub_date > '2005-1-3'
    AND NOT headline = 'Hello'
    order_by(*fields):排序字段
    By default, results returned by a QuerySet are ordered
    by the ordering tuple given by the ordering option in the model’s Meta.
    You can override this on a per-QuerySet basis by using the order_by method
    for example:
    Entry.objects.filter(pub_date__year=2005).order_by('-pub_date', 'headline')
    解释: The result above will be ordered by pub_date descending,
    then by headline ascending.
    The negative sign in front of "-pub_date" indicates descending order.
    Ascending order is implied. To order randomly, use "?", like so:
    随机排序,使用‘?’ : Entry.objects.order_by('?')

    distinct(*fields) :去重复方法
    values(*fields) :获取对应字段的的values列表
    for example:
    >>> Blog.objects.values()
    <QuerySet [{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}]>
    >>> Blog.objects.values('id', 'name')
    <QuerySet [{'id': 1, 'name': 'Beatles Blog'}]>

    all()
    Returns a copy of the current QuerySet (or QuerySet subclass).
    This can be useful in situations where you might want to
    pass in either a model manager or a QuerySet and do further
    filtering on the result. After calling all() on either object,
    you’ll definitely have a QuerySet to work with.
    Methods that do not return QuerySets
    get(**kwargs): 查询结果多条时,报错
    Returns the object matching the given lookup parameters,
    which should be in the format described in Field lookups.
    get() raises MultipleObjectsReturned if more than one object was found.
    The MultipleObjectsReturned exception is an attribute of the model class.

    count():统计个数
    Returns an integer representing the number of objects in the database matching the QuerySet.
    The count() method never raises exceptions.
    for example:
    # Returns the total number of entries in the database.
    Entry.objects.count()

    # Returns the number of entries whose headline contains 'Lennon'
    Entry.objects.filter(headline__contains='Lennon').count()
    latest(field_name=None)
    Returns the latest object in the table,
    by date, using the field_name provided as the date field.
    This example returns the latest Entry in the table, according to the pub_date field:
    Entry.objects.latest('pub_date')

    If your model’s Meta specifies get_latest_by,
    you can leave off the field_name argument to earliest() or latest().
    Django will use the field specified in get_latest_by by default.
    Like get(), earliest() and latest() raise DoesNotExist
    if there is no object with the given parameters.
    Note that earliest() and latest() exist purely for convenience and readability.
    earliest()
    first()
    last()
    exists():
    Returns True if the QuerySet contains any results, and False if not.
          This tries to perform the query in the simplest and fastest way possible,
             but it does execute nearly the same query as a normal QuerySet query.
    exists() is useful for searches relating to both object membership in a QuerySet and to the existence of any objects in a QuerySet,
         particularly in the context of a large QuerySet.

    The most efficient method of finding whether a model with a unique field (e.g. primary_key) is a member of a QuerySet is:
    entry = Entry.objects.get(pk=123)
    if some_queryset.filter(pk=entry.pk).exists():
    print("Entry contained in queryset")
    Which will be faster than the following which requires evaluating and iterating through the entire queryset:
    if entry in some_queryset:
    print("Entry contained in QuerySet")
    update()
    delete()
  • 相关阅读:
    重建Exchange邮件系统的系统邮箱
    枚举算法001
    关于网站备案的44个问题
    wireshack使用
    格言
    程序员遇到BUG的解释
    只要有信心任何事情都可以做成,今天表现不错哦,加油!
    踏实,自信
    学会经营自己的关系
    戒酒
  • 原文地址:https://www.cnblogs.com/luoyeyue/p/7450961.html
Copyright © 2011-2022 走看看