Django writes data model classes

Keywords: Programming Django Database Python SQL

The design of database and table structure is the basis of website. In Django, you don't need to deal with the database directly through SQL statements, but you can create the data model completely with Python classes, and then give Django to complete the operation of creating the database.

Data model class

The data model class needs to be written in the models.py file under the application directory

Write data model

  • The following code demonstrates the class that defines a blog post in models.py
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User


# Create your models here.
class BlogArticles(models.Model):  # The data model classes in Django are all inherited from the django.db.models.Model class.
    # The property of field title is of type CharField and the parameter length is 300
    title = models.CharField(max_length=300)
    """
    //Field author uses ForeignKey to define the relationship between blog posts and users: one user corresponds to multiple posts
    models.CASCADE Indicates cascade deletion
    related_name="blog_posts" Express permission User Class to "blog_posts" Property reverse query to BlogArticles Class instances
    """
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="blog_posts")
    body = models.TextField()
    publish = models.DateTimeField(default=timezone.now)

    """
    ordering = ("-publish",) Regulations BlogArticles Class by publish Display field values in reverse order
    """
    class Meta:
        ordering = ("-publish",)

    """
    //Override the method of the parent class to return the value of the title property when the str() function is used to convert an instance of the class to a string
    """
    def __str__(self):
        return self.title

Building database table based on data model

  1. Create database table file
E:\PycharmProjects\demosite>python manage.py makemigrations
Migrations for 'blog':
  blog\migrations\0002_auto_20190720_1919.py
    - Alter field publish on blogarticles
  1. In the above prompt for execution results, we are told that a BlogArticles model with model number 0001 has been created in the blog/migrations directory. You can enter the following command to view the corresponding SQL statement:
E:\PycharmProjects\demosite>python manage.py sqlmigrate blog 0001
System check identified some issues:

WARNINGS:
blog.BlogArticles.publish: (fields.W161) Fixed default value provided.
        HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If you want to have the current date as default, use `django.utils.timezone.now`
BEGIN;
--
-- Create model BlogArticles
--
CREATE TABLE "blog_blogarticles" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "title" varchar(300) NOT NULL, "body" text NOT NULL, "publish" datetime NOT NULL, "author_id" integer NOT NULL REFERENCES "auth_user" ("id") DEFERRABLE INITIALLY DEFERRED);
CREATE INDEX "blog_blogarticles_author_id_ed798e23" ON "blog_blogarticles" ("author_id");
COMMIT;

In the database, the format of table name is: lowercase application name - lowercase class name

  1. Create database
(demosite) E:\PycharmProjects\demosite>python manage.py migrate
System check identified some issues:

WARNINGS:
blog.BlogArticles.publish: (fields.W161) Fixed default value provided.
        HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If you want to have the current date as default, use `django.utils.timezone.now`
Operations to perform:
  Apply all migrations: admin, auth, blog, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying blog.0001_initial... OK
  Applying sessions.0001_initial... OK

Posted by lJesterl on Sun, 20 Oct 2019 08:10:53 -0700