from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
# one author may have multi post but one post only have one author
# so this is a m2o field
author = models.ForeignKey(User, on_delete=models.CASCADE)
makemigrations
python manage.py makemigrations
this command create a file on blog\migrations\ called 0001_initial.py.
if you want to check what this migrate file will do.
(app_name/migrations/xxxx_initial.py)
python manage.py sqlmigrate blog 0001
execute migrate
python manage.py migrate
then we can enter python shell to execute query command
python manage.py shell
>>> from blog.models import Post
>>> from django.contrib.auth.models import User
>>> User.objects.all()
<QuerySet [<User: jhe>]>
>>> u = User.objects
>>> u.filter(username='jhe')
<QuerySet [<User: jhe>]>
>>> u.filter(username='jhe').first()
<User: jhe>
# check Post records
>>> Post.objects.all()
<QuerySet []>
# Create first record on Post
>>> post_1 = Post(title='Test', content='First content from shell', author=u.get(id=1))
>>> Post.objects.all()
<QuerySet []>
# Save it
>>> post_1.save()
>>> Post.objects.all()
<QuerySet [<Post: Post object (1)>]>
create post class in models.py
makemigrations
this command create a file on
blog\migrations\
called 0001_initial.py. if you want to check what this migrate file will do. (app_name/migrations/xxxx_initial.py)execute migrate
then we can enter python shell to execute query command
python manage.py shell