django-siteflags
django-siteflags copied to clipboard
What is the most efficient way to get all the flags of a user?
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)
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.
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?
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)
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
)
]