我正在使用Django框架创建简单的论坛网站,并且我创建了评论模型,此时我的评论模型与Post有OneToOne关系,这意味着每个时刻都属于特定的帖子,但也有另一个我想提供的功能。每个评论模型都应该有可能与Post对象 OR 与Answer模型相关。答案模型就像在Stack Overflow中一样,你添加一个帖子,另一个用户可以添加答案。我想提一下,答案与Post与OneToOne关系太相关了我认为这样就足够了,并且不需要编辑。 总结:如何允许向Post对象或Answer对象添加注释? 另外我想说我正在考虑创建两个评论模型,即PostComment和AnswerComment,但我得出的结论是非常糟糕的解决方案。
class Post(models.Model):
subject = models.CharField(max_length=100)
description = models.TextField(null=True)
section = models.ForeignKey(Section, on_delete=models.CASCADE, null=True)
author = models.ForeignKey(User, null=True, blank=True)
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
slug = models.SlugField(max_length=100, null=True)
active = models.BooleanField(default=True)
def __str__(self):
return self.subject
def publish(self):
self.published_date = timezone.now()
self.save()
def close(self):
self.active = False
self.save()
class Comment(models.Model):
content = models.CharField(max_length=600)
post = models.OneToOneField(Post, on_delete=models.CASCADE)
author = models.ForeignKey(User, null=True, blank=True)
published_date = models.DateTimeField(blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return "Comment to post: {0} added by {1} at {2}.".format(self.post.subject, self.author, self.published_date)
class Answer(models.Model):
content = models.TextField()
post = models.OneToOneField(Post, on_delete=models.CASCADE)
author = models.ForeignKey(User, null=True, blank=True)
published_date = models.DateTimeField(blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return "Answer to post: {0} added by {1} at {2}.".format(self.post.subject, self.author, self.published_date)
答案 0 :(得分:1)
请记住,类的顺序在Python中很重要。将注释类放在最后,以便您可以在Post和Answer之间创建一对一的关系。在当前位置,您只能使用Post。
class Post(models.Model):
##
class Answer(models.Model):
##
class Comment(models.Model):
post = models.OneToOneField(Post, on_delete=models.CASCADE, null=True, blank=True)
answer = models.OneToOneField(Answer, on_delete=models.CASCADE, null=True, blank=True)
答案 1 :(得分:0)
如果一个Post对象可以有多个注释,我认为你的注释字段中需要ForeignKey。关于答案,也许你可以在你的评论中添加另一个字段,指向对象答案,如果答案中有几条评论,则使用ForeignKey。