2
我正在创建Django应用程序,与论坛类似的东西。其中一个观点应该显示讨论列表,最后的文字旁边会显示。Django在eachother旁边取两个对象
class Discussion(models.Model):
<snip>
topic = models.CharField(max_length=512)
class DiscussionPost(models.Model):
<snip>
target = models.ForeignKey(Discussion)
author = models.ForeignKey(User)
content = models.TextField(max_length=16000)
creation_date = models.DateTimeField(auto_now_add=True)
对于标准的Django查询,我必须每页获取约50次(每次讨论一次)。
DiscussionPost.objects
.filter(target=some_discussion)
.annotate(last_post=Max('creation_date'))
.filter(creation_date=F('last_post'))
我试图通过添加场last_post = models.ForeignKey(DiscussionPost, null=True)
来讨论,改变DiscussionPost“保存”方法类似这样的工作,围绕此:
def save(self, *args, **kwargs):
if self.pk == None:
i_am_new = True
else:
i_am_new = False
super(DiscussionPost, self).save(*args, **kwargs)
if i_am_new:
self.target.last_post=self
self.target.save()
但是这使得循环依赖,根本不会编译。
有没有人知道解决这个问题的方法?这似乎很容易,但我坚持......
感谢您的帮助:)当你写的,我发现了一些在Django文档[链接](https://docs.djangoproject.com/en/dev/ref/车型/场/#递归关系)。 – Bugari 2012-03-07 18:23:12