博客五部曲之二 - 高级博客


1203 浏览 5 years, 3 months

14 模型管理器和实例方法

版权声明: 转载请注明出处 http://www.codingsoho.com/

上一章节在关联评论和帖子的内容时花了大篇幅去获取它的内容,本节通过Model Manager来简化这个操作。

将原先下面的代码放倒ModelManger来实现

    content_type = ContentType.objects.get_for_model(Post)
    obj_id = instance.id
    comments = Comment.objects.filter(content_type=content_type,object_id=obj_id)

在model里添加

class CommentManager(models.Manager):
    def filter_by_instance(self, instance):
        content_type = ContentType.objects.get_for_model(instance.__class__)
        obj_id = instance.id
        qs = super(CommentManager,self).filter(content_type=content_type,object_id=obj_id)
        return qs

没什么特别之处,基本就是前面view的实现,只是把固定的Post模型改成了通用的instance.__class__

将view的调用处修改为

comments = Comment.objects.filter_by_instance(instance)

这样,以后view的调用处只要这一句就可以了。

我们还可以更进一步,不需要再view处传递,直接通过实例方法传递给模板

class Post(models.Model):
    @property
    def comments(self):
        instance = self
        qs = Comment.objects.filter_by_instance(instance)
        return qs

然后在模板用{{instance.comments.all}}显示。用property装饰之后,就可以在view里直接用instance.comments进行访问,否则得用函数instance.comments()

所有,有很多种方法可以显示,选一种即可。

最后,使用bootstrap的引用格式来美化评论的显示。

https://getbootstrap.com/docs/3.3/css/#type-blockquotes