One 、 Preparatory work , Create databases and tables , Details click 《Django Learning notes ( 6、 ... and )MySQL To configure

1. Create a project

2. Create an application

3. change

4. change

5. Synchronous data

Two 、 install IPython convenient debug

sudo apt-get install ipython3

After successful installation, use python shell Will automatically enter Ipython In the interactive interpreter , No installation Ipython Just the first two lines , Only into Python shell in .

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]:

If enabled directly Ipython3 Words , You can also see the following code , But because it's not in that position , There will be ImproperlyConfigured error . The reason is to start directly Ipython Interactive interpreter , No settings Django Environment variables of DJANGO_SETTINGS_MODULE, Add environment variables to run , So it's recommended to run it directly Python shell command .

ImproperlyConfigured Traceback (most recent call last)
<ipython-input-1-df0154182ca0> in <module>()
----> 1 from blog.models import Person /home/lee/MySQL1/blog/ in <module>()
1 from django.db import models
----> 3 class Person(models.Model):
4 name = models.CharField(max_length=10)
5 /home/lee/MySQL1/blog/ in Person()
3 class Person(models.Model):
----> 4 name = models.CharField(max_length=10)
6 def __str__(self): /home/lee/.local/lib/python3.5/site-packages/django/db/models/fields/ in __init__(self, *args, **kwargs)
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/ 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/ 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/ 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))
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.


The solution is to write the following three lines of code , among MySQL1 Is the name of the project , In this article, the project name is MySQL1.

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

3、 ... and 、 Add data

1. The first way , Create instance object of class , Modify the properties of an object , preservation .

In [1]: from blog.models import Person
In [2]: p1=Person()
In [3]:'Lee'
In [4]:

2. The second way , Directly when the class is instantiated , The constructor gives the field properties directly , preservation .

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

3. The third method , Call... In the class manager create Method .

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

MySQL Database content :

Four 、 Query data

1. Query all

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

If it happens, it's all Person: Person Object , Please be there. blog/ Add __str__, Return character method .

from django.db import models
class Person(models.Model):
name = models.CharField(max_length=10) def __str__(self):

2. Query specific conditions ,filter amount to =,exclude amount to !=,get Get the object directly instead of 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>

5、 ... and 、 Modifying data

Modify on the basis of query data , One is filter modify , The other is get modify , The two methods are different , Because the objects of the query results are different .

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

6、 ... and 、 Delete data

To delete data, add one on the basis of query data .delete() that will do .

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})

Last in the series :Django Learning notes ( 6、 ... and )MySQL To configure

Next in the series :

Django Learning notes ( 7、 ... and ) Basic operation of database ( Add check to delete ) More articles about

  1. MongoDB Learning record ( Four ) - MongoDB Of &quot; Add check to delete &quot; Operation of the &quot; Change &quot;

    There are several ways to update documents : db.collection.updateOne(filter, update, options) db.collection.updateMany(filter, upd ...

  2. MongoDB Learning record ( 3、 ... and ) - MongoDB Of &quot; Add check to delete &quot; Operation of the &quot; check &quot;

    Find the method to use : db.collection.find() Find all documents db.collection.find({}) perhaps db.collection.find({}) Specify a key value pair db.collect ...

  3. MongoDB Learning record ( Two ) - MongoDB Of &quot; Add check to delete &quot; Operation of the &quot; increase &quot;

    If the set for inserting documents does not exist , Then the collection will be created db.collection.insertOne() insertOne by collection Insert a document , If the document _id Field not specified ,MongoDB Meeting ...

  4. SQL Server 2012 Learning notes 3 Add check to delete

    Now let's give some examples " Add check to delete " The sentence of select * from UserInfor -- Find all fields select username,UserId from UserInfor -- ...

  5. ylb: Create database 、 surface , Add, query, modify, delete statements to the table

    ylbtech-SQL Server:SQL Server- Create database . surface , Add, query, modify, delete statements to the table SQL Server Create database . surface , Add, query, modify, delete statements to the table . 1,ylb: Create database . surface , Adding, checking, modifying and deleting words in the table ...

  6. EF Add, query, modify and delete of single entity and various additions and deletions of data associated with master-slave tables Revision

    Contents of this article EF Adding, checking, modifying and deleting a single entity Add a single entity Query a single entity Modify individual entities Delete a single entity EF In the master-slave table associated data of various additions, deletions, changes and queries increase ( Add data from table . Add master-slave table data ) Inquire about ( Find the data in the slave table according to the master table . According to the slave table ...

  7. DOM A summary of the addition, search, modification and deletion of trees

    DOM A summary of the addition, search, modification and deletion of trees Abstract : Yes HTML DOM The operation is the front end JavaScript The necessary skills in programming , This article is my own comment on DOM Summary of tree operations , It's mainly a list of methods , There is less talk about principles , It is suitable for people to sort out ideas or review One ...

  8. JS Array , Object addition, query, modification and deletion ( Multi grammatical contrast )

    Horizontal comparison of data structure , increase , check , Change , Delete Suggest : When using data structures , Give priority to Map and Set( Consider the uniqueness of data ), Abandon traditional arrays and Object, Especially when the data structure is more complex Array Map And Arra ...

  9. Django Study note 3 Database input data

    Let's assume that django_blog project , establish blog Of app , stay There's more Blog class , Synchronize database , And set up the corresponding table . Specific reference Django Learn the related commands of note 2 . So this article mainly introduces ...

Random recommendation

  1. Android APK Signature ( forward )

    Cordova 3.5 by Android APK Signature , Build publishable APK Program files   Ren Xia   2014-06-07 00:04   Mobile development    Grab the sofa   16,288 views  Catalog [ hide ] ...

  2. android Next asynchttp Library for session Support for

    Default asynchttp Library does not support session, It needs to be configured by users cookie To deal with it , Direct post support session Code for package; import andr ...

  3. How should we understand JavaScript How the engine works series

  4. android Call the project

    Will the project A Make it android library project. Setup project A, Right click ->Properties->Android, take Is library Item selected , then Apply. Setup project B, Right click -& ...

  5. green tftpserver:tftpd32 Configuration of

    Embedded development is indispensable to use TFTP service , Its main function is to transfer files to the target board . tftpd32.exe It's the most commonly used one today TFTPserver, Today, let's introduce its configuration method . 1. From here Download the new version number tftpd3 ...

  6. SCALA Functional programming in

    Demonstrates the value function , Anonymous functions , Closure ... Other specific applications , It's still in production .. This is the end of it .. Other SAM,CURRY, Higher order function , aggregate , Generic , Implicit class .. these , It's better to find a special book to have a deep understanding ... C:\User ...

  7. Java Basic chapter 2

  8. on-line Django project python2 To 3 Upgrade diary

    I've done a crazy thing these two days , It takes less than a working day to put an online Django Project language version from python2 Upgrade to Python31. A grammatical change in dictionaries Python2.7: if dict1.haskey( ...

  9. carding :python— Method calls in the same class

    Why is this issue mentioned here suddenly ? Because when I practice what I have learned through comprehensive practice , Suddenly, I feel that the application of some knowledge points is always unsuccessful , So I went over the textbook to review , Always feel right , But when we think about it further “ Since it's right , Why does it always fail in the program ...

  10. Oracle Date function of database

    Today I'd like to introduce to you oracle Usage of date function in data . I don't say much nonsense , Let's see oracle They give us those functions ? 1.sysdate purpose : Get current system time . 2.to_date(' Character type ',' Date class ...