django models

The module that operates on the database in python is models.

1. Create a database

models.py

from django.db import models

# Create your models here.

class Employee(models.Model):
    name=models.TextField(max_length=50)

    def __str__(self):
        return self.name

  Then execute the add database command:

python manage.py makemigrations
python manage.py migrate

  Login database authentication.

2. Query/manipulate the database

1. Via the django shell

python manage.py shell

1. Three ways to add data to the database

>>> from fir.models import Employee
>>> emp=Employee()
>>> emp.name='zhoujielun'
>>> emp.save()
>>>
>>> emp2=Employee(name='lixiang')
>>> emp2.save()
>>>
>>> emp3=Employee.objects.create(name='zhouxingxing')
>>> res=Employee.objects.all()
>>> res
<QuerySet [<Employee: zhoujielun>, <Employee: ligen>, <Employee: zouzou>, <Employee: zouzou>, <Employee: zhoujielun>, <Employee: lixiang>, <Employee: zhouxingxing>]>
>>> for i in res:
...     print(i)
...
zhoujielun
leagues
zouzou
zouzou
zhoujielun
lixiang
zhouxingxing

  Query/add database via view function

#views.py
from fir.models import Employee

def test(req):
    res=Employee.objects.all()
    return render(req,'test.html',locals())

#urls.py
from fir import views

urlpatterns = [
    path(r'blog/test/',views.test)
]

#test.html
<html>
    <head>
        <title>test</title>
    </head>
    <body>
        {% for item in res %}
        {{forloop.counter}} {{item}}
        {% endfor %}
    </body>
</html>

  

Guess you like

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