Course Content
Django: First Dive
Django: First Dive
2. Write the First Page
4. Working with Database
How to create a Model?
Let's write your first model!
Django creates the models.py
in your apps automatically. Find the models.py
in your created app and work with it.
To write a model, you need to use the models
package imported from django.db
.
Now, you can create tables in your database. Django is connected to SQLite3 by default.
To create a table, you need to create a model class using the following syntax:
The Model
class has needed tools for your models and connecting inherited classes to the database. TableName
is the name of the table that you want to create.
The next step is defining the attributes of the table. The id
field is created by default, you don't need to implement this attribute.
To implement other attributes (fields), you can define the class attributes and assign different fields to them.
Look at the example:
Here, the CharField
, FloatField
, and IntegerField
are classes that can receive arguments (attributes). These arguments are field parameters that can be defined by Database Management System (DBMS). In our case, DBMS is SQLite3.
Note
The existing fields you can see in the Django documentation.
Everything was clear?