Django Generic Relation woth parent model

628 views Asked by At

I have created a model Comments. I want store reply in same table Comment.

class Comment(models.Model):
  user = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE)
  content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
  text = models.CharField(max_length=300, blank=False, null=False)
  object_id = models.PositiveIntegerField()  
  timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)

  content_object = GenericForeignKey('content_type', 'object_id')

  # Relation
  reply = GenericRelation(Comment, related_query_name='reply')
  like = GenericRelation(Like, related_query_name='like')

Here i am getting this error !!

  reply = GenericRelation(Comment, related_query_name='reply')
  NameError: name 'Comment' is not defined

How can i set this relationship ?

1

There are 1 answers

2
token On

You're getting this error, because Comment is not defined yet.

Replace

reply = GenericRelation(Comment, related_query_name='reply')

with

reply = GenericRelation('self', related_query_name='reply')