我正在创建 Django 应用程序,带有类似论坛的东西。其中一个 View 应显示讨论列表,并在其旁边显示最后的书面帖子。
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()
但这会产生循环依赖,并且根本无法编译。
有谁知道解决这个问题的方法吗?这看起来很容易,但我被困住了......
最佳答案
要解决你的循环依赖:
问题是:当您在讨论中 FK 时,DiscussionPost 尚未声明。 将尚未声明的模型名称放在引号中。
models.ForeignKey('DiscussionPost', null=True)
关于python - 在 Django 中获取彼此相邻的两个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9606786/