ARJhe / Django_tutorial-Blog

0 stars 0 forks source link

Create Web App - Post #2

Open ARJhe opened 4 years ago

ARJhe commented 4 years ago
  1. create post class 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 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)
  2. makemigrations

    python manage.py makemigrations

    20012502 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

    20012503

  3. execute migrate

    python manage.py migrate

    20012504

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)>]>