django - Filtering related objects for each item in a queryset -


i have model (we'll call 'item') can tagged users. tags specific each user. so, example, item can have multiple tags multiple users. need display list of items user. within list i'd able show tags each item logged in user owns. i'm hoping there easy way of achieving this, i've been unable find helpful in docs. in advance.

class item      tags = manytomanyfield('tags.tag')  class tag      user = foreignkey('auth.user') 

so collect queryset of items display on page, , list through them in template. i'd able show tags owned logged in user each item in queryset.

{% item in items %}       {% tag in item.tags %}             display tags owned logged in user       {% endfor %} {% endfor %} 

this i'd achieve ^

one approach add property item class, user_tags can set in view , filter tags match logged in user.

# models.py class item(models.model):     ...      user_tags = []     ...  # views.py items = item.objects.all().select_related('tags') item in items:     item.user_tags = [tag tag in item.tags if tag.user = logged_in_user] 

then in template can iterate on them:

{% item in items %}     {{ item }}     {% tag in item.user_tags %}         {{ tag }}{% ifnot forloop.last %}, {% endif %}     {% endfor %} {% endfor %} 

caveat: i'm not best @ sql anymore, it's entirely possible there's way pass parameter select_related join tags user id. unfortunately i'm out of time morning, check in on you.


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -