Django 学习笔记(七)数据库基本操作(增查改删)

一、前期准备工作,创建数据库以及数据表,详情点击《Django 学习笔记(六)MySQL配置

1.创建一个项目

2.创建一个应用

3.更改settings.py

4.更改models.py

5.同步数据

二、安装IPython方便debug

sudo apt-get install ipython3

安装成功后用python manage.py shell 会自动进入Ipython交互解释器中,没有安装Ipython只有前两行代码,只进入到Python shell 中。

Python 3.5.2+ (default, Sep 22 2016, 12:18:14)
Type "copyright", "credits" or "license" for more information. IPython 2.4.1 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details. In [1]:

如果直接启用Ipython3的话,也可以出现以下代码,但是由于没有定位在那个位置,将会出现ImproperlyConfigured错误。原因是直接启动Ipython交互解释器,没有设置Django的环境变量DJANGO_SETTINGS_MODULE,添加上环境变量即可运行,所以还是推荐直接运行Python manage.py shell命令。

ImproperlyConfigured                      Traceback (most recent call last)
<ipython-input-1-df0154182ca0> in <module>()
----> 1 from blog.models import Person /home/lee/MySQL1/blog/models.py in <module>()
1 from django.db import models
2
----> 3 class Person(models.Model):
4 name = models.CharField(max_length=10)
5 /home/lee/MySQL1/blog/models.py in Person()
2
3 class Person(models.Model):
----> 4 name = models.CharField(max_length=10)
5
6 def __str__(self): /home/lee/.local/lib/python3.5/site-packages/django/db/models/fields/__init__.py in __init__(self, *args, **kwargs)
1059
1060 def __init__(self, *args, **kwargs):
-> 1061 super(CharField, self).__init__(*args, **kwargs)
1062 self.validators.append(validators.MaxLengthValidator(self.max_length))
1063 /home/lee/.local/lib/python3.5/site-packages/django/db/models/fields/__init__.py in __init__(self, verbose_name, name, primary_key, max_length, unique, blank, null, db_index, rel, default, editable, serialize, unique_for_date, unique_for_month, unique_for_year, choices, help_text, db_column, db_tablespace, auto_created, validators, error_messages)
170 self.db_index = db_index
171 self.db_column = db_column
--> 172 self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
173 self.auto_created = auto_created
174 /home/lee/.local/lib/python3.5/site-packages/django/conf/__init__.py in __getattr__(self, name)
54 """
55 if self._wrapped is empty:
---> 56 self._setup(name)
57 val = getattr(self._wrapped, name)
58 self.__dict__[name] = val /home/lee/.local/lib/python3.5/site-packages/django/conf/__init__.py in _setup(self, name)
37 "You must either define the environment variable %s "
38 "or call settings.configure() before accessing settings."
---> 39 % (desc, ENVIRONMENT_VARIABLE))
40
41 self._wrapped = Settings(settings_module) ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

ImproperlyConfigured

解决办法是将下面三行代码写上,其中MySQL1是项目的名称,在本文中项目名称是MySQL1。

import os,django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "MySQL1.settings")
django.setup()

  

三、添加数据

1.第一种方式,创建类的实例对象,修改对象的属性,保存。

In [1]: from blog.models import Person

In [2]: p1=Person()

In [3]: p1.name='Lee'

In [4]: p1.save()

2.第二种方式,直接在类实例化的时候,构造方法直接给予字段属性,保存。

In [5]: p2=Person(name='Kein')

In [6]: p2.save()

3.第三种方法,调用类管理器中的create方法。

In [7]: p3=Person.objects.create(name='KeinLee')

MySQL数据库内容:

Django 学习笔记(七)数据库基本操作(增查改删)

四、查询数据

1.查询全部

In [8]: Person.objects.all()
Out[8]: <QuerySet [<Person: Lee>, <Person: Kein>, <Person: KeinLee>]>

如果出现全部都是Person: Person Object ,请在blog/models.py中添加__str__,返回字符方法。

from django.db import models

class Person(models.Model):
name = models.CharField(max_length=10) def __str__(self):
return self.name

2.查询特定条件,filter相当于=,exclude相当于!=,get直接得出对象而不是QuerySet对象。

In [9]: Person.objects.filter(name='Lee')
Out[9]: <QuerySet [<Person: Lee>]> In [10]: Person.objects.exclude(name='Lee')
Out[10]: <QuerySet [<Person: Kein>, <Person: KeinLee>]> In [11]: Person.objects.get(name='Lee')
Out[11]: <Person: Lee>

  

五、修改数据

在查询数据的基础上修改,一个是filter修改,另一个是get修改,这两种方法是不一样的,因为查询结果的对象不一样。

In [12]: Person.objects.filter(name='Kein').update(name='Ben')
Out[12]: 1 In [13]: p=Person.objects.get(name='Lee') In [14]: p.name='Alen' In [15]: p.save()

  

六、删除数据

删除数据就直接在查询数据的基础上加一个.delete()即可。

In [16]: Person.objects.get(name='Lee').delete()
Out[16]: (1, {'blog.Person': 1}) In [17]: Person.objects.filter(name='Kein').delete()
Out[17]: (1, {'blog.Person': 1}) In [18]: Person.objects.exclude(name='Lee').delete()
Out[18]: (1, {'blog.Person': 1})

  

系列上一篇:Django 学习笔记(六)MySQL配置

系列下一篇:

上一篇:Object.keys()的理解


下一篇:A sample of procedure in using