top of page

Django Notes 6: Create Data Models

Django already provides the space for us to store data models in models.py. The class Customer is made in such syntax:

from django.db import models

# Create your models here.
class Customer(models.Model):
	name = models.CharField(max_length=200, null=True)
	phone = models.CharField(max_length=200, null=True)
	email = models.CharField(max_length=200, null=True)
	date_created = models.DateTimeField(max_length=200, null=True)
	def __str__(self):
		return self.name

the __str__(self) function is optional. It is a function that what format of the name we can see inside the Django admin console once a new instance is made.


After creating the data model, we need to migrate the data model to our database. There are a lot of table creating commands handled by Django. What we need to do is tell Django we have updated the data model by calling a command in terminal:

python manage.py makemigrations

Then we call another command to really creating the new table for us:

python manage.py migrate

In order to link all those table to our admin console, we need to configue our admin.py.

from django.contrib import admin
from .models import Customer

# Register your models here.
admin.site.register(Customer)

If all the things are done we can see the new data model in the admin page:

ree

 
 
 

Recent Posts

See All
Create Git Server from my NAS

Recently I am creating a git server in my NAS by following the tutorial here: https://dotblogs.com.tw/bowwowxx/2014/08/14/146249 I have...

 
 
 
Django Notes 8: Query of Database

There are several examples for query the objects in the following: https://github.com/divanov11/crash-course-CRM/blob/Part-8---data-to-te...

 
 
 

Comments


  • Facebook - White Circle
  • Instagram - White Circle
  • LinkedIn - White Circle

© 2017 by Johnny. Make it just for fun.

bottom of page