python - 在 Django 中获取彼此相邻的两个对象

标签 python django

我正在创建 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)

参见:https://stackoverflow.com/a/9606701/884453

关于python - 在 Django 中获取彼此相邻的两个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9606786/

相关文章:

python - 中止陷阱 : when using a Python script with Tkinter and Pyglet

python - mod_wsgi 在压力下失败

Python Pandas 多条件赋值

django - facebook-messenger-bot 错误 : When & why this error raised "(#100) Length of param name_placeholder[text] must be less than or equal to 640"

python - 如何限制一名用户投一票?

python - 使用 Wea​​syprint 的 PDF 输出不显示图像(Django)

django - RabbitMQ 保持连接运行很长时间

python - DBSCAN 中的预计算距离矩阵

python - Instagram 抓取

python - Django - 在处理端点请求之前验证 AWS Cognito token 是否有效