我一直在使用 django-simple-history 跟踪我的应用程序中评论的编辑历史,我已经能够跟踪已编辑的评论,但刚刚意识到在创建时也在跟踪条目。即在创建时将新条目添加到历史表中。
我的模型
class Comments(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateField(auto_now=True)
body = models.TextField(max_length=200)
is_Child = models.BooleanField(default=False)
author = models.ForeignKey(User, related_name='author_rel',
on_delete=models.CASCADE)
article = models.ForeignKey(Article, related_name='comments',
on_delete=models.CASCADE, null=False)
parent = models.ForeignKey('self', null=True, blank=True,
on_delete=models.CASCADE, related_name='threads')
history = HistoricalRecords()
def __str__(self):
return str(self.body)
class Meta:
ordering = ['-created_at']
我的视图类
class CommentsListView(ListCreateAPIView):
serializer_class = CommentSerializer
permission_classes = (IsAuthenticatedOrReadOnly,)
queryset = Comments.objects.all()
renderer_classes = (CommentJSONRenderer,)
def create(self, request, slug, *args, **kwargs):
serializer_context = {
'request': request,
'article': get_object_or_404(Article, slug=self.kwargs["slug"])
}
article = Article.objects.filter(slug=slug).first()
data = request.data
serializer = self.serializer_class(
data=data, context=serializer_context)
serializer.is_valid(raise_exception=True)
serializer.save(author=self.request.user, article_id=article.pk)
return Response(serializer.data, status=status.HTTP_201_CREATED)