How to use python model

coldplay.xixi
Release: 2020-08-25 11:55:16
Original
9268 people have browsed it

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',
    }
}
Copy after login

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
Copy after login

will generate some management tables

3. Then create a new model

First import the models package

Add

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

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 执行迁移
Copy after login

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()
Copy after login

Delete

book=Book.objects.get(id=1)
book.delete()
Copy after login

Execute the delete method after obtaining the object with id 1

Check

book=Book.objects.all()
Copy after login

Query all Book objects and return a collection

book=Book.objects.get(id=1)
Copy after login

Get the Book object with id 1

book=Book.objects.filter(title__icontains="hello")
Copy after login

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

Change

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

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()
Copy after login

Then add the manager to the model

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

When using Yes

count=Book.myobjects.get_book_count("hello")
Copy after login

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')
Copy after login

Add the manager to the model

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

When used, it is

queryset=Book.pyhton_objects.get_query_set()
Copy after login

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
Copy after login
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!

Related labels:
source:php.cn
Statement of this Website
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 [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!