Django数据模型代码片段

blog

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User

class Post(models.Model):

    STATUS_CHOICES = (

        ('draft','Draft'),

        ('published','Published')

    )

    title = models.CharField(max_length=250)

    slug = models.SlugField(max_length=250,unique_for_date='publish')

    author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='blog_post')

    body = models.TextField()

    publish = models.DateTimeField(default=timezone.now)

    created = models.DateTimeField(auto_now_add=True)

    updated = models.DateTimeField(auto_now=True)

    status = models.CharField(max_length=10,choices=STATUS_CHOICES,default='draft')


    class Meta:

        ordering = ('-publish',)


    def __str__(self):

        return self.title

https://docs.djangoproject.com/en/2.0/ref/models/fields/ 可以找到所有字段类型。

模型中的Meta类包含元数据。告诉Django在查询数据库时默认按降序对publish字段中的结果进行排序。我们使用负前缀指定降序。通过这样做,最近发布的帖子将首先显示。

__str__()方法是对象的默认人类可读表示形式。Django会在很多地方使用它,比如管理站点。

你可能感兴趣的:(django)