0

我一直在使用 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)
4

1 回答 1

0

这是行为的一部分,但如果您不想存储该信息,您可以做的是在信号django-simple-history中删除该类型的记录。

from django.dispatch import receiver
from simple_history.signals import (
    post_create_historical_record
)

@receiver(post_create_historical_record)
def post_create_historical_record_callback(sender, **kwargs):
    history_instance = kwargs['history_instance']
    if history_instance.get_history_type_display() == "Created":
        history_instance.delete()
于 2019-02-05T15:36:56.610 回答