简体   繁体   中英

Django filter based on field of latest related model

I have a model Post and Comment and i'm trying to filter a list of posts to only show the ones that have a certain boolean value (here called epic_bool ) on the latest comment.

I am trying it as follows:

object_list = Post.objects.all()

newest = Comment.objects.filter(
    post=OuterRef('pk')
).order_by('-upload_date')
Post.objects.annotate(
    is_true=Subquery(newest.values('epic_bool')[:1])
)
object_list = object_list.filter(is_true=True)

But I get FieldError

Cannot resolve keyword 'is_true' into field. Choices are: ...

I don't understand why because i'm trying to annotate and not resolve a field??

solution:

    newest = Comment.objects.filter(
        post=OuterRef('pk')
    ).order_by('-upload_date')
    object_list = object_list.annotate(
        epic_bool=Subquery(newest.values(epic_bool)[:1])
    ).filter(epic_bool=True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM