Database (a) - to create database tables and populate data by django

django can not create the database, only the ability to create database tables, therefore, we must first establish a connection to the database when the database.

In the models.py

from django.db import models

class Publisher(models.Model):
  id = models.AutoField(primary_key=True)
  name = models.CharField(max_length=64,null=False,unique=True)

  def __str__(self):
    return "publisher_name:{}".format(self.name)

class Book(models.Model):
  id = models.AutoField(primary_key=True)
  title = models.CharField(max_length=128,null=False)
  publisher = models.ForeignKey(to=Publisher,related_name="books")

  def __str__(self):
    return "book_title:{}".format(self.title)

class Author(models.Model):
  id = models.AutoField(primary_key=True)
  name = models.CharField(max_length=16,null=False)
  book = models.ManyToManyField(to="Book")

  def __str__(self):
    return "author_name:{}".format(self.name)

Enter the address of the project,

Enter python manage.py makemigrations

 

Enter python manage.py migrate

 We django generated by the four tables: where is the app for the prefix, I have here a person; an association exists between the table name with _ connections, and name.

 

 Next we fill in some data,

Python manage.py shell at the input path to open item django terminal:

 

 We give an example:

 

 For your convenience, we have other data to fill in manually navicat. Finally results are as follows (person_publisher, person_author, person_book, person_author_book):

 

Guess you like

Origin www.cnblogs.com/xiximayou/p/11778983.html