如何在Django模型中使用GenericRelation自相关?

时间:2019-05-04 20:01:47

标签: django django-models contenttypes

我想将Comment用于两件事: 1-发表评论 2-评论评论

我可以使用评论模型对帖子发表评论:

me = User.objects.get(pk=1)
post = Post.objects.get(pk=1)
comment = Comment.objects.create(user=me, body='the comment', content_object=post)
post.comments.all()
<QuerySet [<Comment: the comment>, <Comment: post level comment>]>

但是我无法从Comment实例本身访问评论:

reply = Comment.objects.create(user=me, body='reply level comment', content_object=comment)
reply.content_object
<Comment: the comment>
comment.replies.all()
<QuerySet []>

如您所见,访问Comment.replies.all()不会返回与其自身相关的Comment实例。

这是我的模型。py:

from django.db import models
from django.contrib.auth import get_user_model
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
from taggit.managers import TaggableManager

User = get_user_model()


# Create your models here.


class Comment(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="comments")
    date = models.DateTimeField(auto_now_add=True)
    body = models.CharField(max_length=1000)
    replies = GenericRelation("self", related_query_name='replies')
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey("content_type", "object_id")

    def __str__(self):
        return self.body


class Post(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="posts")
    title = models.CharField(max_length=260)
    body = models.TextField()
    is_published = models.BooleanField(default=True)
    comments = GenericRelation(Comment, related_query_name='comments')
    views = models.IntegerField(default=0)
    tags = TaggableManager()

    def __str__(self):
        return self.title

0 个答案:

没有答案