The Django Model (database)

Source: Internet
Author: User
Tags connection pooling install django pip install django django tutorial

The Django model is database-related, database-related code is generally written in models.py, and Django supports Sqlite3, MySQL, PostgreSQL and other databases, Only need to configure in settings.py, do not change the code in the models.py, the rich API is very convenient to use.

First, open the model file, modify the code

 from Import  class person (models. Model):    = models. Charfield (max_length=30)    = models. Integerfield ()

We have created a new person class that inherits from models. Model, a person has a name and age. There are two types of field, and more field types can refer to the link at the end of the tutorial.

Description: This section is about creating the data tables and their structures that our business needs, and when we do this, we create the tables, which are ignored if they are created, and are updated if there are any modifications.

Second, synchronize the database

Before synchronizing the database, we need to set up the database, if you are using SQLite3, There is no need to configure, if you are using other Django built-in database, the reference Django tutorial can also be configured quickly, I use the database is SQL Server, Because it is not one of the data that Django itself supports, a third-party module is required to configure the database. Encountered a lot of pits in the middle, the final configuration is successful, now the main steps to introduce:

1, third-party library django-pyodbc-azure, using this library is based on Django 1.10.4 and PYODBC 3.0 or newer

    1. Install Pyodbc and Django
    2. Install django-pyodbc-azure
Pip Install Django-pyodbc-azure

Here are an example of the database settings:

DATABASES = {    'default': {         'ENGINE':'Sql_server.pyodbc',         'NAME':'django_test',         'USER':'SA',         'PASSWORD':'*****',         'HOST':'127.0.0.1',         'PORT':"',          'OPTIONS': {              'Driver':'SQL Server Native Client 11.0',              'mars_connection': True,},},}#set this to False if you want to turn off PYODBC ' s connection poolingdatabase_connection_pooling = False

Once the setup is complete, you can synchronize the data and execute the following two code:

Python manage.py Makemigrationspython manage.py Migrate

We'll see that Django generates a series of tables.

Django provides a rich API, and the following shows how to use it.

 from Import person >>> Person.objects.create (name="Jason", age=28)< Person:person object>

How to query data from a database

>>> Person.objects.get (name="Jason")<person:person Object >

We used a. Objects.get () method to query out the objects that meet the criteria, but you notice that there is no, the query results show <person: Person object; Here does not show the relevant information with the WEIZHONGTU, if the user is more than can not know the query out who the end is, the query results are correct, we re-modify the people/models.py

You cannot have __ (double underscore) in fields such as name and age, because there are special meanings in the Django QuerySet API (for relationships, inclusions, case-insensitive, what starts or ends, dates greater than less, regular, etc.)

Also cannot have the keyword in Python, name is legal, Student_name is also legal, but student__name illegal, try, class, continue is not legal, because it is a Python keyword (import Keyword Print (keyword.kwlist) All keywords can be typed)

 from Import  class person (models. Model):    = models. Charfield (max_length=30)    = models. Integerfield ()     def__str__(self):            return self.name

Knowledge Supplement:

There are several ways to create a new object:

    1. Person.objects.create (Name=name,age=age)
    2. p = person (name= "WZ", age=23)

P.save ()

    1. p = person (name= "TWZ")

P.age = 23

P.save ()

    1. Person.objects.get_or_create (name= "Wzt", age=23)

This method is a good way to prevent repetition, but it is relatively slow to return a tuple, the first is the person object, the second is true or false, and the new one returns True, which returns false if it already exists.

Getting an object has the following methods:

    1. Person.objects.all ()
    2. Person.objects.all () [: 10] slicing operation, get 10 people, not support negative index, slice can save memory
    3. Person.objects.get (name=name) #get是用来获取一个对象的, if you need to get some people who meet the criteria, use the filter
    4. Person.objects.filter (name= "abc") # Equals Person.objects.filter (name__exact= "abc") name Strictly equals "abc" person
    5. Person.objects.filter (name__iexact= "abc") # NAME is ABC but not case-sensitive, you can find ABC, ABC, ABC, these are eligible
    6. Person.objects.filter (name__contains= "abc") # Person with "ABC" in Name
    7. Person.objects.filter (name__icontains= "abc") #名称中包含 "ABC", and ABC is case insensitive
    8. Person.objects.filter (name__regex= "^ABC") # Regular expression query
    9. Person.objects.filter (name__iregex= "^ABC") # Regular expressions are not case-sensitive, filter is found to meet the conditions, of course, there are also excluded to meet certain conditions
    10. Person.objects.exclude (name__contains= "wz") # excludes the person object containing WZ
    11. Person.objects.filter (name__contains= "ABC"). Exclude (AGE=23) # Find out the name contains ABC, but the exclusion age is 23 years old

Reference Documentation:

Django Models Official Tutorial: https://docs.djangoproject.com/en/dev/topics/db/models/

Fields related official documents: https://docs.djangoproject.com/en/dev/ref/models/fields/

The Django Model (database)

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.