码迷,mamicode.com
首页 > 编程语言 > 详细

python 项目随笔-2

时间:2017-08-30 00:50:09      阅读:254      评论:0      收藏:0      [点我收藏+]

标签:com   随机   not   err   保存数据   whether   datetime   进入   client   

python版本 3.6.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()

python 项目随笔-2

标签:com   随机   not   err   保存数据   whether   datetime   进入   client   

原文地址:http://www.cnblogs.com/luoyeyue/p/7450961.html

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