Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to write data model classes in Django

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the relevant knowledge of "how to write data model classes in Django". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

The design of database and table structure is the foundation of a website. In Django, instead of dealing with the database directly through SQL statements, the data model is created entirely with the classes of Python, and then handed over to 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 in the application directory

Write a data model

The following code demonstrates a class that defines a blog post in models.py

From django.db import modelsfrom django.utils import timezonefrom django.contrib.auth.models import User# Create your models here.class BlogArticles (models.Model): the data model classes in # Django inherit 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 specify the relationship between blog posts and users: one user corresponding to multiple articles models.CASCADE means to cascade delete related_name= "blog_posts" to allow instances of User class to reverse query to instances of BlogArticles class "" author = models.ForeignKey (User, on_delete=models.CASCADE) with "blog_posts" attribute. Related_name= "blog_posts") body = models.TextField () publish = models.DateTimeField (default=timezone.now) "" ordering = ("- publish",) specifies that the instance of the BlogArticles class displays "class Meta: ordering = ("-publish ",)"the method of overriding the parent class in reverse order by the value of the publish field. When you use the str () function to convert an instance of this class to a string, return the value of the title property "" def _ _ str__ (self): return self.title builds the database table based on the data model.

Create a database table file

E:\ PycharmProjects\ demosite > python manage.py makemigrationsMigrations for 'blog': blog\ migrations\ 0002_auto_20190720_1919.py-Alter field publish on blogarticles

In the prompt for the execution result above, we are told that a BlogArticles model has been created in the blog/migrations directory with the model number 0001. You can enter the following command to view the corresponding SQL statement:

E:\ PycharmProjects\ demosite > python manage.py sqlmigrate blog 0001System 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

The table name format in the database is: lowercase application name _ lowercase class name

Create a database

(demosite) E:\ PycharmProjects\ demosite > python manage.py migrateSystem 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, sessionsRunning 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... This is the end of OK's "how to write data model classes in Django". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report