python - 如何使用附加过滤的相关对象作为 Django 中的字段来获取结果?

标签 python django python-3.x django-views django-orm

我想在一个查询中获取所有数据,因此我需要通过相关对象的过滤器(而不是通过父对象过滤器)添加相关对象的一些字段结果。

def get_queryset(self):
        return Mailbox.objects\
            .filter(owner=self.request.user.id)\
            .prefetch_related('letter_set')\
            .annotate(
                new_letter_count=Count(
                    'letter',
                    filter=Q(letter__read_at=None)
                ),
                total_count=Count('letter'),
                latest_letter_datetime=Max('letter__created_at'),


                ### #################### ###
                ### THE QUESTION IS HERE ###
                ### #################### ###

                latest_letter_CONTENT= #(What code here could be work?)#

                ### I wnat to get the latest letter content


            )

最佳答案

好吧,我会假设模型Letter中有一个ForeignKey指向模型MailBox来回答这个问题。

您可以使用 Subquery为此:

# I'm assuming here a couple of things:
# The fields content and date_created exist in your Letter model, 
# if there is no date created field, use instead whatever you are using for
# establish some sort of order creation.
MailBox.objects.annotate(
    last_letter_content = Subquery(
        Letter.objects.filter(mailbox=OuterRef('pk')).order_by('-date_created').values('content')[:1]
    )
)

关于python - 如何使用附加过滤的相关对象作为 Django 中的字段来获取结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56086239/

相关文章:

python - 在 WSGI 容器中使用扭曲的词

python - 表单背后的逻辑(request.POST 或 None)

python-3.x - Python 中的重采样

python - 将整数作为字符串存储在数据库中的缺点

python - 在 Python 中求解非线性方程组 (scipy.optimize.fsolve)

python 时间范围验证器

python - 如果 python 中没有有效的解析输出,如何避免创建空记录器文件?

python - django 评论 : how to specify the sort direction?

python - 返回条件语句

python - 重定向 sys.stdout 时 numpy savetxt 乱序