Django Learning Notes (vii) Basic operation of the database (additional search and deletion)

Source: Internet
Author: User
Tags change settings class manager

First, pre-preparation work, create database and data table, details Click "Django Learning Note (vi) MySQL configuration"

1. Create a project

2. Create an App

3. Change settings.py

4. Change models.py

5. Synchronizing Data

Second, installation Ipython convenient debug

sudo apt-get install Ipython3

After the installation is successful, the Python manage.py shell automatically enters the Ipython interaction interpreter, with no installation Ipython only the first two lines of code, only into the Python shell.

Python 3.5.2+ (default, Sep, 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 Sys Tem.object?   

If you enable Ipython3 directly, you can also get the following code, but the improperlyconfigured error will occur because there is no location. The reason is to start the Ipython interactive interpreter directly, without setting the Django environment variable django_settings_module, add the environment variable to run, so it is recommended to run the Python manage.py shell command directly.

improperlyconfigured Traceback (most recent)<ipython-input-1-df0154182ca0>inch<module>()----> 1 fromBlog.modelsImport Person/home/lee/mysql1/blog/models.pyinch<module>()      1 fromDjango.dbImportModels2----> 3classPerson (models. Model):4 name = models. Charfield (max_length=10)      5/home/lee/mysql1/blog/models.pyinchPerson ()2 3classPerson (models. Model):----> 4 name = models. Charfield (max_length=10)      5 6def __str__(self):/home/lee/.local/lib/python3.5/site-packages/django/db/models/fields/__init__. pyinch __init__(Self, *args, * *Kwargs)1059 1060def __init__(Self, *args, * *Kwargs):-1061 Super (Charfield, self).__init__(*args, * *Kwargs)1062Self.validators.append (validators. Maxlengthvalidator (self.max_length))1063/home/lee/.local/lib/python3.5/site-packages/django/db/models/fields/__init__. pyinch __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)Self.db_index =Db_index171 Self.db_column =db_column--172 Self.db_tablespace = Db_tablespaceorsettings. Default_index_tablespace173 self.auto_created =auto_created174/home/lee/.local/lib/python3.5/site-packages/django/conf/__init__. pyinch __getattr__(self, name)54"""if self._wrapped is empty:---> Self._setup (name), val = GetAttr (self._ wrapped, name) self.__dict__[name] = VAL/HOME/LEE/.LOCAL/LIB/PYTHON3.5/SITE-PACKAGES/DJANGO/CONF/__INIT__.P                 Y in _setup (self, name) PNs "You must either define the environment variable%s" 38 "or call Settings.configure () before accessing settings." ---> (desc, environment_variable)) self._wrapped = Settings (settings_module ) improperlyconfigured:requested setting Default_index_tablespace, but settings is not configured. You must either define the environment variable Django_settings_module or call Settings.configure () before accessing Setti NGS.
improperlyconfigured

The workaround is to write the following three lines of code, where MySQL1 is the name of the project, and the project name in this article is MySQL1.

Import Os,djangoos.environ.setdefault ("Django_settings_module", "Mysql1.settings") Django.setup ()

  

Third, add data

1. The first way, create an instance object of the class, modify the properties of the object, save.

In [1]: From blog.models import Personin [2]: P1=person () in [3]: P1.name= ' Lee ' in [4]: P1.save ()

2. The second way, directly in the class instantiation, the constructor method directly gives the field properties, save.

In [5]: P2=person (name= ' kein ') in [6]: P2.save ()

3. The third method invokes the Create method in the class manager.

In [7]: P3=person.objects.create (name= ' Keinlee ')

MySQL Database content:

Iv. Querying data

1. Search All

In [8]: Person.objects.all () out[8]: <queryset [<person:lee>, <person:kein>, <person:keinlee>] >

If all occurrences are Person:person Object, add __str__ in blog/models.py to return the character method.

From django.db import modelsclass person (models. Model):    name = models. Charfield (max_length=10)        def __str__ (self):        return Self.name

2. Query for specific conditions, filter equivalent to =,exclude equivalent to!=,get directly to the object rather than the Queryset object.

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>

  

V. Modification of data

On the basis of query data modification, one is filter modification, and the other is get modification, the two methods are different, because the query results of the object is not the same.

In [a]: Person.objects.filter (name= ' kein '). Update (name= ' Ben ') out[12]: 1In []: P=person.objects.get (name= ' Lee ') in []: P.name= ' Alen ' in []: P.save ()

  

Vi. deletion of data

Delete data directly on the basis of the query data add a. Delete ().

in [+]: Person.objects.get (name= ' Lee '). Delete () out[16]: (1, {' Blog. Person ': 1} "in []: Person.objects.filter (name= ' kein '). Delete () out[17]: (1, {' Blog. Person ': 1} "in []: Person.objects.exclude (name= ' Lee '). Delete () out[18]: (1, {' Blog. Person ': 1})

  

Series Prev: Django Learning Notes (vi) MySQL configuration

Next Article series:

Django Learning Notes (vii) Basic operation of the database (additional search and deletion)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.