Django_03.数据模型: Post

数据模型

# blog/models.py
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User

class Post(models.Model):
    title = models.CharField(max_length=128)
    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

迁移

python manage.py makemigratons
python manage.py migrate

shell

In [1]: from blog.models import Post

In [2]: from django.contrib.auth.models import User

In [3]: User.objects.all()
Out[3]: ]>

In [4]: User.objects.first()
Out[4]: 

In [5]: vi = User.objects.first()

In [6]: vi.id
Out[6]: 1

In [7]: vi.pk
Out[7]: 1

In [8]: vi = User.objects.get(id=1)

In [6]: p1 = Post(title='Blog One', content='First Post Content!', author=vi)

In [7]: p1.save()

In [8]: Post.objects.first()
Out[8]: 

>>> p2 = Post(title='Blog Two', content='Second Post Content!', author_id=vi.id)
>>> p2.save()

In [11]: p2.author.email
Out[11]: '[email protected]'

In [13]: vi.post_set.all()  # 注意语法  .modelName_set.all()
Out[13]: , ]>

In [14]: vi.post_set.create(title="Post Three", content="Post 3 Content!")
Out[14]: 

>>> Post.objects.all()
, , ]>

在 views.py 中使用 数据库中的数据

# blog/views.py
from django.shortcuts import render
from .models import Post

def index(request):
    context = { "posts": Post.objects.all() }
    return render(request, 'blog/index.html', context)

其中,context 中的数据,被传入了 网页模板中。
在网页模板中调用的语法:


{% extends 'base.html' %}

{% block title %}
    Blog - Index
{% endblock %}

{% block content %}
    

Blog home index

{% for post in posts %}

{{ post.title }}

by {{ post.author }} on {{ post.date_posted }}

{{ post.content }}

{% endfor %} {% endblock %}

时间格式:

参考链接: docs-djangoproject.com-builtins-date
在网页模板中使用这样格式:

{{ post.date_posted | date:"d M Y" }}

在 admin 页面中注册 Post 类型

# blog/admin.py
from django.contrib import admin
from .models import Post

admin.site.register(Post)

你可能感兴趣的:(Django_03.数据模型: Post)