django|django 数据相关

简单样例 博客类和评论类 每个评论都只能属于一个博客,一个博客可以有很多评论
【django|django 数据相关】blog用于储存文章,comment用于储存文章的评论

class Post(models.Model): author = models.CharField('作者', max_length=50) title = models.CharField('标题', max_length=200, unique=True) body = models.TextField('正文') createDate = models.DateTimeField('创建时间', default=now) updateDate = models.DateTimeField('修改时间', default=now)def __str__(self): return self.title class Meta: ordering = ['-createDate']def GetPost(title=''): try: s=Post.objects.get(title=title) s.createDate=str(s.createDate) return s except: return '查询错误'class Comment(models.Model): name = models.CharField('名称',max_length=50) body = models.TextField('评论内容') createDate = models.DateTimeField('创建时间', default=now) updateDate = models.DateTimeField('修改时间', default=now) post = models.ForeignKey(Post,on_delete=models.CASCADE)def __str__(self): return self.body class Meta: ordering = ['createDate']

查找某一blog对应的所有comment :
from posting.models import Comment,Post b=Blog.objects.get(id=1) comment = post.comment_set.all() #评论集 comment = comment.order_by('-createDate') #按照发送时间排序

添加一条数据
from posting.models import Comment,Post p=Post(author='No.2',title='second title',body='222222') p.save()

修改一条数据
from posting.models import Comment,Post p=Post.objects.get(pk=2) p.body='22222' p.save()

删除一条数据
from posting.models import Comment,Post p=Post.objects.get(pk=2) p.delete()

    推荐阅读