如何使用django rest框架在后端突出显示文章的一部分

时间:2019-01-31 04:13:05

标签: python django-rest-framework highlight

这就是我创建文章的方式

`CreateArticleView(ListCreateAPIView)类:     “”         类处理文章的创建     “”“

permission_classes = (IsAuthenticatedOrReadOnly,)
serializer_class = ArticleSerializer
renderer_classes = (ArticleJSONRenderer,)
queryset = Article.objects.all()

def list(self, request, *args, **kwargs):
    queryset = Article.objects.all()
    serializer = self.serializer_class(queryset, many=True)
    return Response(serializer.data)

def post(self, request, *args, **kwargs):
    article = request.data.get('article', {})

    if self.request.user.is_verified is False:
        message = error_messages['email_verification']
        return Response(message, status=status.HTTP_401_UNAUTHORIZED)

    context = {"request": request}
    serializer = self.serializer_class(data=article, context=context)
    serializer.is_valid(raise_exception=True)
    serializer.save(author=request.user)
    return Response(serializer.data, status=status.HTTP_201_CREATED)`

`

这是我查看一篇文章的方式,因此,我想获取一篇文章,并能够突出显示文章的多个部分并设法对其进行评论

class GetUpdateDeleteArticle(RetrieveUpdateDestroyAPIView):
permission_classes = (IsAuthenticated,)
renderer_classes = (ArticleJSONRenderer,)
queryset = Article.objects.all()
serializer_class = ArticleSerializer
lookup_field = 'slug'

@staticmethod
def validate_author(request, article):
    if request.user.pk != article.author_id:
        message = error_messages['unauthorised']
        return Response(message, status.HTTP_403_FORBIDDEN)

def get(self, request, *args, **kwargs):
    """
    :param request: user requests to get an article
    :param kwargs: slug field is passed in the url
    :return: data and response if article exists
    """

    try:
        article = Article.objects.get(slug=kwargs['slug'])
    except Article.DoesNotExist:
        message = error_messages['article_404']
        return Response(message, status=status.HTTP_404_NOT_FOUND)

    serializer = ArticleSerializer(
        instance=article, context={'request': request})
    return Response(serializer.data, status=status.HTTP_200_OK)

1 个答案:

答案 0 :(得分:0)

这更多是模型级别的设计决策,更少的是API问题。我将使用以下数据库设计:

模型突出显示,用于存储对文章的引用,文本突出显示部分的开始索引和结束索引。因此,大致是这样的:

class Highlight(models.Model):
    article = models.ForeignKey(Article, related_name='highlights')
    start = models.PositiveIntegerField()
    end = models.PositiveIntegerField()

然后创建一个注释模型。一种常见的设计是使用generic relations,以便注释可以与应用程序中的任何模型一起使用。这样的东西就足够了:

class Comment(TimeStampedModel):
    text = models.TextField(blank=False)
    author = models.ForeignKey(User, related_name='comments')
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

您现在可以围绕该设计构建一个API,客户可以通过发送突出显示的文本的文章ID,开始和结束索引来创建突出显示。也可以使用突出显示的ID创建评论。检索文章要点也应该很容易实现。