0

I have a model (we'll call it 'item') that can be tagged by users. Tags are specific to each user. So, for example, an item can have multiple tags by multiple users. I need to display a list of all items to a user. Within that list I'd like to be able to only show the tags for each item that the currently logged in user owns. I'm hoping that there is a fairly easy way of achieving this, but I've been unable to find anything helpful in the docs. Thanks in advance.

class Item
     tags = ManyToManyField('tags.Tag')

class Tag
     user = ForeignKey('auth.User')

So I collect a queryset of items to display on a page, and list through them in the template. I'd like to be able to only show the tags owned by the currently logged in user for each item in the queryset.

{% for item in items %}
      {% for tag in item.tags %}
            DISPLAY TAGS OWNED BY LOGGED IN USER
      {% endfor %}
{% endfor %}

This is what I'd like to achieve ^

  • can you show an example of what it is you're trying to achieve? – Gabriel Amram Mar 24 '14 at 11:27
  • Can you explain what is ambiguous about the example I gave? I'm not sure how I can demonstrate my problem any more clearly in code. –  Mar 24 '14 at 11:29
  • @GabrielAmram I've just added an example. Let me know if it's unclear. –  Mar 24 '14 at 11:32

1 Answers1

0

One approach is to add a property to your Item class, user_tags which you can set in your view and then filter the tags to only those who match the logged in user.

# models.py
class Item(models.Model):
    ...

    user_tags = []
    ...

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

Then in your template you can iterate over them:

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

Caveat: I'm not the best at SQL anymore, so it's entirely possible that there's a way to pass an extra WHERE parameter to select_related to only join tags for that user id. Unfortunately I'm out of time this morning, but I will check back in on you.

Brandon Taylor
  • 33,823
  • 15
  • 104
  • 144
  • I'm not trying to filter the items based on which tags a user owns - I'm trying to filter the tags for each item based on the logged in user. So some results in the queryset may not have any tags related to the logged in user. –  Mar 24 '14 at 11:37
  • I think you need to re-phrase your question. I'll adjust my answer. – Brandon Taylor Mar 24 '14 at 11:40
  • I've rephrased it slightly. It might help to assume that the queryset contains all items (Item.objects.all()), but the tags displayed for each item must only be related to the logged in user. –  Mar 24 '14 at 11:44
  • Thanks so much. I've added some template code in my original post that might help to demonstrate it better. –  Mar 24 '14 at 11:49