【问题标题】:getting the count of titles opened by a user only if the first entry also belongs to the same user仅当第一个条目也属于同一用户时,才获取用户打开的标题数
【发布时间】:2020-06-09 16:03:07
【问题描述】:

标题模型:

class Title(models.Model):
    first_author = models.CharField(max_length = 150)
    title = models.CharField(max_length = 150, unique = True)
    created_date = models.DateTimeField(auto_now=True)
    title_url= models.CharField(max_length = 150)

入门型号:

    class Entry(models.Model):
    title = models.ForeignKey("titles.title", on_delete= models.CASCADE)
    user = models.ForeignKey("auth.user", on_delete= models.CASCADE)
    created_date = models.DateTimeField(auto_now_add=True)
    updated_date = models.DateTimeField(auto_now=True)
    content = models.TextField(max_length=10000,)

在我的博客中,当用户打开一个标题时,用户还必须编写第一个条目(最低 created_date)。如果标题中没有其他条目,则删除第一个条目时,标题也会被删除。所以我只想在标题的第一个条目仍然属于同一用户时才计算用户打开的标题。

我唯一的想法是让用户打开所有标题:

titles= Title.objects.filter(first_author=user.username)

然后遍历标题并检查第一个标题是否仍然属于同一用户,如果是,则将其添加到计数中。

但是由于它需要遍历查询集,因此查询对象不再是惰性的,并且需要花费太多时间。

我想知道是否有一种方法可以仅通过一个 ORM 来实现。

【问题讨论】:

  • 第一个条目是created_date最低的条目?
  • 是的就是那个。

标签: python django database orm


【解决方案1】:

我们可以用子查询来检查,例如:

from django.db.models import Subquery, OuterRef, Q

titles = Title.object.annotate(
    first_entry=Subquery(Entry.objects.filter(
        title=OuterRef('pk')
    ).order_by('created_date').values('user')[:1]
    )
).filter(
    first_author=user.username,
    first_entry=user
)

【讨论】:

  • 非常感谢 Williem,但是这个返回的是一个空的查询集。
  • first_author=user.username 永远不会是真的 :)
  • 嗯 first_author 不是外键,所以我认为它可能是真的。我保存标题的方式 --- newTitle= Title(title=title,first_author=request.user.username,title_url=url)
  • @mattarello:已编辑,但不使用 fk 似乎是一个严重的反模式。
  • 非常感谢您的帮助,最终解决方案完美运行。
猜你喜欢
  • 1970-01-01
  • 2021-11-22
  • 2015-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-30
  • 1970-01-01
  • 2021-11-10
相关资源
最近更新 更多