如何在Django中进行LEFT OUTER JOIN QuerySet - 多对一

问题描述 投票:1回答:1

我有两个模型:Image(filename,uploaded_at)和Annotation(作者,质量,... fk图像)。

图像可以具有多个注释,并且注释属于一个图像。

我想构建一个查询集,该查询集可以获取满足某些条件的所有注释(包括与图像的关系,因此我也可以显示图像字段)。

一切都很好,直到这里,但我想显示没有创建注释的图像(左外连接),不知道我怎么能继续这样做?

为了澄清我正在尝试获取数据,所以我可以构建一个这样的表:

Image name, Image date, Annotation author, Annotation Quality
image 1   , 2019      , john             , high
image 2   , 2019      , doe              , high
image 3   , 2019      , null             , null
image 4   , 2014      , doe              , high

也许我正在使用错误的方法,我使用Annotation作为主要模型,但是我似乎没有办法显示没有Annotation的图像,哪种有意义,因为没有Annotation。这就是我正在做的事情:

Annotation.objects.select_related('image').filter(Q(image__isnull=True)
 | Q(other condition))

但是,如果我使用Image作为主模型,关系是一个图像的许多注释,所以我不能使用select_related,我不确定prefetch_related是否适用于我需要的。我不知道如何正确获取数据。我试过这个:

Image.objects.prefetch_related('annotations').filter(Q(annotations__isnull=True) | Q(other condition))

prefetch_related似乎没有对查询产生任何影响,而且我希望将Annotation数据放在flat /同一行中(即第1行:图像1,注释1;第2行:image1,注释2,等)而不是必须做image.annotation_set ...因为这不符合我的需要。

任何建议将非常感激。

谢谢!

django django-queryset django-orm
1个回答
2
投票

如果您需要外连接,则必须是左连接,正如您正确假设的那样。所以你必须从Image模型开始。要获得平面表示而不是嵌套的Annotation对象,请使用values(),它返回字典的查询集(而不是模型对象):

queryset_of_dictionaries = (Image.objects
    .filter(Q(annotations__isnull=True) | Q(other condition))
    .values('name', 'date', 'annotations__author', 'annotations__quality',
            # etc. – you have to enumerate all fields you need
    )
    # you'll probably want the rows in a particular order
    .order_by(
        # a field list like in values()
    )
)

# accessing the rows
for dic in queryset_of_dictionaries:
    print(f'Image name: {dic["name"]}, quality: {dic["annotations__quality"]}')
© www.soinside.com 2019 - 2024. All rights reserved.