Building a Python web framework from scratch - Django (3)

Django supports multiple databases such as PostgreSQL, MySQL, SQLite, Oracle. Django models provide a unified interface to implement CURD operations on data, so you can easily switch databases.

 The following will introduce the use of the Django model. The author takes the MySQL database as an example:

Step ↓

  1. Install mysqlclient for Django's interaction with the database:

     The ubuntu system is as follows:

    sudo apt-get install libmysql-dev
    sudo apt-get install libmysqlclient-dev
    sudo apt-get install python-dev
    sudo pip install mysqlclient
     The windows system is as follows:

     (1)  https://www.lfd.uci.edu/~gohlke/pythonlibs/#Download  the version installation package corresponding to the python version and the corresponding operating system bit, such as python 2.7, 64-bit operating system download: mysqlclient-1.3. 7-cp27-none-win_amd64.zip

     (2) Unzip the installation package, enter the directory to open cmd, and use the pip install command to install:

    pip install mysqlclient-1.3.7-cp27-none-win_amd64
       Note: If pip is not installed, please install it yourself.

     

  2. Configure database parameters: Open settings.py in the Django project and configure as follows:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql', # or use mysql.connector.django
            'NAME': 'ds', #database name
            'USER':'root', #database user
            'PASSWORD': '1234', #Database password
            'HOST':'localhost', #Database server IP
            'PORT':'3306', #port
        }
    }
     
  3. Create an app: Enter the project root directory and execute:
    django-admin.py startapp TestModel
     Windows system execution:
    django-admin startapp TestModel

    Do the following configuration in settings.py, and configure the just-built app TestModel into the project:

    INSTALLED_APPS = (
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'TestModel', # add this
    )
     

     

     Description: What is the difference between a project and an application? An application is a web application that does something, such as a blogging system. A project is a collection of configurations and applications for a specific website. A project can contain multiple applications. An application can be used in multiple projects.
    HelloWorld
    | - TestModel
    |   |-- __init__.py
    |   |-- admin.py
    |   |-- models.py
    |   |-- tests.py
    |   `-- views.py
     
  4. Build a model: Open models.py and write a model:
    class Movie(models.Model):
        moviename = models.CharField('movie name', max_length=100)
        createtime = models.DateTimeField('Published time', auto_now_add=True)
        updatetime = models.DateTimeField('Change time', auto_now=True)
        publishtime = models.CharField('publish time', max_length=10, blank=True)
        types = models.CharField('类型', max_length=200, blank=True)
        area = models.CharField('地区', max_length=200, blank=True)
        language = models.CharField('语言', max_length=200, blank=True)
        def __unicode__(self):
            return self.moviename
    
    
    class Outsource(models.Model):
        num = models.IntegerField('Number of episodes', default=1)
        outfilelink = models.CharField('External file link',max_length=500)
        movie = models.ForeignKey(Movie,verbose_name="电影")
        def __unicode__(self):
            return self.num
     Description: We can create a model in models.py by creating a class that integrates model.Model. Django can automatically create a table in the database according to models. The attribute name is the field name of the table. Models.IntegerField and so on indicate the data type of the field. The default parameter indicates the default value. The first parameter can be displayed in the Django admin form. We It can be understood as a comment, but Django will not really add comments to the database table. models.ForeignKey can specify foreign keys. A TV series has many levels, so use the episode as a foreign key in the resource table. In addition, the Django model also supports relationships such as ManyToMany and OneToOne. blank=True specifies that the field can be blank, but not by default. null=True means that Django will fill empty fields with nulls, which are not allowed by default. max_length specifies the field length.
  5. Create migrations and create table structure:
    $ python manage.py migrate # Create table structure
    $ python manage.py makemigrations TestModel # Generated migrations
    $ python manage.py migrate TestModel # create table structure
      Description: You can see the migrations package in the app directory, it will record every change, we can open the file inside to read it. Open the database and we can see that the table structure has been built. Note: If the model is modified and the above command is executed, Django will automatically modify the table structure and will not clear the existing data in the table, which is very convenient.
  6. CURD operation on data: (here I post some scattered code)
    movie = get_object_or_404(Movie, id=id) #This method is used in views, if there is no record, it will return 404
    movie.playcount += 1
    movie.save() #If there is data in the database, modify it. If it does not exist, insert it. Equivalent to merge statement in SQL
    
    n = movie.avaliblesum=movie.outsource_set.count() #Returns how many episodes the TV series has, see the model definition example above
    print n
    
    for outsource in movie.outsource_set.all(): ##Return each episode of the TV series
        print outsource.outfilelink
    #Filter, equivalent to where statement, the following means (where weight>=5 and classkey=#{key} order by createtime desc limit 0 12)
    movies = Movie.objects.filter(weight__gte=5).filter(classkey=key).order_by('-createtime')[:12]
    #The following means (where keyword like '%#{key}%' or moviename like '%#{key}%' ), to use 'or', the Q object must be used
    allmovies = Movie.objects.filter(Q(keyword__icontains=key) | Q(moviename__icontains=key))
    
    # delete data with id=1
    # Test.objects.filter(id=1).delete()
    
    # delete all data
    # Test.objects.all().delete()
    
    # Modify one of the name fields with id=1, and then save, which is equivalent to UPDATE in SQL
    test1 = Test.objects.get(id=1)
    test1.name = '222'
    test1.save()
    
    # another way
    #Test.objects.filter(id=1).update(name='222')
    
    # modify all columns
    # Test.objects.all().update(name='222')
    
    
    # Get all data rows through the all() of the objects model manager, which is equivalent to SELECT * FROM in SQL
    list = Test.objects.all()
    	
    # get a single object
    response3 = Test.objects.get(id=1)
    
     Note: Here are just some common examples. For details, please see the official documentation. Django models are very powerful and can replace most of the common native SQL statements. Of course, using Django also supports the introduction of native SQL statements, which will not be introduced here. And it is not necessary to use Django model to use Django. Django is a low-coupling framework, and each of its modules can be chosen according to needs and preferences.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326171521&siteId=291194637