Home  >  Article  >  Backend Development  >  How to use python model

How to use python model

coldplay.xixi
coldplay.xixiOriginal
2020-08-25 11:55:169423browse

The usage of python model is: 1. The model is added, the code is [book=Book(title="hello go")]; 2. The model is deleted, the code is [book=Book.objects.get (id=1), book.delete()].

How to use python model

【Related learning recommendations: python tutorial

The usage of python model is:

1. First is the database configuration

Generally, new django projects are configured For sqlite as the database

Usually MySQL is used in projects

So first modify the configuration

Modify it in settings.py of the project

Change the original configuration sqlite to your own attributes

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'USER':'root',
        'PASSWORD':'',
        'NAME':'djangouse',
        'HOST':'localhost',
    }
}

USER fill in the user name of MySQL

PASSWORD fill in the password of MySQL

NAME fill in the name of the database used, You need to create this in MySQL yourself

Note: Remember to open MySQL before using the model

2. The command line has changed a lot in the new version of django

The following are the main commands about the model

python manage.py check Check whether the model has spelling errors

python manage.py makemigrations Generate a migration file for the changes in the model

python manage.py migrate Execute migration

Usually after creating the app and database

First execute

python manage.py migrate

will generate some management tables

3. Then create a new model

First import the models package

Add

from django.db import models
class Book(models.Model):
    title=models.CharField(max_length=100)
    def __unicode__(self):
        return self.title

to the app’s models.py The model has a title field with a maximum length of 100

unicode. This method returns the content displayed when the Object is queried. The default display is Object

, and then it is executed in sequence

python manage.py check  检查model是否有拼写错误
python manage.py makemigrations 将model的改变生成一个迁移文件
python manage.py migrate 执行迁移

Then querying the database used will find that there is an additional table with a name containing book

4. Next is the addition, deletion, checking and modification of the model

add

book=Book(title="hello django")
book.save()

Delete

book=Book.objects.get(id=1)
book.delete()

Execute the delete method after obtaining the object with id 1

Check

book=Book.objects.all()

Query all Book objects and return a collection

book=Book.objects.get(id=1)

Get the Book object with id 1

book=Book.objects.filter(title__icontains="hello")

Get the collection of Book objects containing hello in the title field

Change

book=Book.objects.get(id=1)
book.title="django"
book.save()

5. The next model Advanced use - manager

manager is an encapsulation of some common methods of model

There are methods for obtaining values, and there are also methods for obtaining object collections

Look at the values ​​obtained How to create a manager

Create a new class inherited from models.Manager in the model.py in the app

class BookManager(models.Manager):
    def get_book_count(self,keyword):
        return self.filter(title__icontains=keyword).count()

Then add the manager to the model

class Book(models.Model):
    title=models.CharField(max_length=100)
    myobjects=BookManager()

When using Yes

count=Book.myobjects.get_book_count("hello")

This returns the number of objects whose names contain book

What if you want to obtain a collection of objects with special conditions?

Create a new manager

class PythonManager(models.Manager):
    def get_query_set(self):
        return super(PythonManager,self).get_query_set().filter(title__icontaions='hello')

Add the manager to the model

class Book(models.Model):
    title=models.CharField(max_length=100)
    myobjects=BookManager()
    pyhton_objects=PythonManager()

When used, it is

queryset=Book.pyhton_objects.get_query_set()

This will return a collection of Book objects whose name contains hello

6. The next step is to use the background page to manage the model

First enter

python manage.py createsuperuser
in the terminal

The above is the detailed content of How to use python model. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn