django中建立一個Model

crystalnsd發表於2017-09-10

step1

建立一個應用(python manage.py startapp books) 這裡建立一個叫books應用
,然後在settings中的INSTALLED_APPS引數中加上應用,如下:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'books',
]

step 2

建立一個model類,一個類對應資料庫中的一張表如下
打book>models.py編寫下面程式碼:

from django.db import models

# Create your models here.
class Publisher(models.Model):
    name = models.CharField(max_length= 30)
    address = models.CharField(max_length= 50)
    city = models.CharField(max_length=50)
    state_province = models.CharField(max_length= 100)
    country = models.CharField(max_length= 100)
    websit = models.URLField()

class Author(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)
    email = models.EmailField()

然後執行:(django 1.9 之前執行python manage.py syncdb)
python manage.py migrate
python manage.py makemigrations book
這樣資料庫中就會生成兩張表
books_author |
books_publisher

step 3 model增刪改查:

1插入資料

from books.models import Author
a1 =Author(first_name = 'yin',last_name = 'xiong', email = '352322399')
a1.save()

執行完成,可以看到資料庫多了一條資料
| 1 | yin | xiong | 352322399 |

#

相關文章