【问题标题】:Django Generic Relation woth parent modelDjango 与父模型的通用关系
【发布时间】:2020-06-26 11:51:08
【问题描述】:

我创建了一个模型Comments。我想在同一张桌子上回复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')

我收到了这个错误!!

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

如何设置这种关系?

【问题讨论】:

  • 我会在回复行中查看“self”而不是 Comment。 stackabuse.com/recursive-model-relationships-in-django
  • 我无法扭转它。 c = Comment.objects.get(pk=1) c.reply.all() 它返回 <QuerySet []> 但我在此评论中有回复。
  • 您在创建评论时一定有错字。使用代码示例创建一个新问题(在视图和模型中创建链接的问题)
  • 你能举个例子吗??
  • 嗯,类似 c= Comment(reply=comment_to_reply_to) 然后 c.save()

标签: python django django-models generic-relations django-generic-relations


【解决方案1】:

您收到此错误,因为尚未定义 Comment

替换

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

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

【讨论】:

  • 我怎样才能扭转它??
  • c = Comment.objects.get(pk=1) c.reply.all() 它返回 <QuerySet []> 但我在此评论中有回复。
猜你喜欢
  • 1970-01-01
  • 2016-09-22
  • 2022-01-27
  • 2014-01-22
  • 2019-04-15
  • 1970-01-01
  • 2020-12-25
  • 2014-01-22
  • 2011-01-06
相关资源
最近更新 更多