django-siteflags icon indicating copy to clipboard operation
django-siteflags copied to clipboard

What is the most efficient way to get all the flags of a user?

Open mymonetizingsdk opened this issue 3 years ago • 4 comments

Let's say I have an Article model that inherits from ModelWithFlag. Users can bookmark articles and I want to list all the bookmarks a user has on their profiles. How do I do that in a view?

Would something like this work?

user = User.objects.get(pk = 1)
bookmarks = Article.get_flags_for_types([user], status = 1)

mymonetizingsdk avatar Jan 13 '22 22:01 mymonetizingsdk

That rather would be something like:

Article.get_flags_for_types([Article], user=user, status=1)

Note here that get_flags_for_types exposed in Article is only a convenience to access a generic method, so you need to pass [Article].

This'd give you information about flags for Articles set by user, and having status=1.

Speaking of efficiency, currently there's no way to select or prefetch data related to flags (i.e. information from articles themselves), so for that you'd probably need to make another db query. That might be the way for siteflags improvement.

idlesign avatar Jan 14 '22 02:01 idlesign

Thank you very much for your reply. Sorry, I'm new to this. At this point, calling that method gives me something like this:

{<class 'articles.models.Article'>: [<Flag: articles | Article:6 status 1>, <Flag: articles | Article:5 status 1>]}

How do I query the articles from this dictionary? Would you kindly point me in the right direction?

hsb-tonmoy avatar Jan 14 '22 03:01 hsb-tonmoy

Something like the following I think

article_ids = [flag.object_id for flag in Article.get_flags_for_types([Article], user=user, status=1)[Article]]
arcticles = Article.objects.filter(id__in=article_ids)

idlesign avatar Jan 14 '22 05:01 idlesign

There're improvements now available in master:

articles = [
    flag.linked_object 
    for flag in Article.get_flags_for_type(
        user=user, 
        status=1, 
        with_objects=True
    )
]

idlesign avatar Jan 28 '22 07:01 idlesign