django - Queryset, get only one of reverse relationships -


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() gives me bars. there way can latest bar each foo, using 1 query?

you want use prefetch object, here in docs.

prefetch() lets filter query, in example:

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 

Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -