【问题标题】:Queryset, get only one of reverse relationshipsQueryset,只获取一种反向关系
【发布时间】:2015-05-29 17:45:43
【问题描述】:
class Foo(models.Model):
    name = CharField
    createdat = DateTimeField

class Bar(models.Model):
    rel = ForeignKey(Foo, related_name='bars')
    createdat = DateTimeField

Foo.prefetch_related('bars').all() 给了我所有的酒吧。有什么方法我只能使用一个查询为每个Foo 获取最新的Bar

【问题讨论】:

    标签: django django-queryset


    【解决方案1】:

    您想使用Prefetch 对象,即here in the docs

    Prefetch() 允许您过滤查询,就像您的示例中那样:

    queryset = Bar.objects.latest('createdat')
    latest_bars = Foo.objects.prefetch_related(
        Prefetch(
            'bars', 
            queryset, 
            to_attr="latest_bar"
        )
    )
    the_latest_bar_for_first_foo = latest_bars[0].latest_bar
    

    【讨论】:

    • 其实这样不行。 latest() 不返回查询集,而是返回一个实例。
    【解决方案2】:

    试试这个:

    A.prefetch_related('bars').latest()
    

    【讨论】:

    • 这将给我最新的As(一个结果行),这不是我想要的。我想要所有结果,每个Foo 都有最新的Bar
    猜你喜欢
    • 2015-07-16
    • 2021-11-16
    • 2020-04-24
    • 1970-01-01
    • 2020-01-15
    • 1970-01-01
    • 2016-08-18
    • 1970-01-01
    • 2018-07-05
    相关资源
    最近更新 更多