In django-taggit, how to get tags for objects that are associated with a specific user?
Asked Answered
R

1

8

I have a series of objects that are associated with specific users, like this:

from django.db import models
from django.contrib.auth.models import User
from taggit.managers import TaggableManager

class LibraryObject(models.Model):
    title = models.CharField(max_length=255)
    owner = models.ForeignKey(User)
    tags = TaggableManager()
    class Meta:
        abstract = True

class Book(LibraryObject):
    summary = models.TextField()

class JournalArticle(LibraryObject):
    excerpt = models.TextField()

# ...etc.

I know that I can retrieve all tags like this:

>>> from taggit.models import Tag
>>> Tag.objects.all()

But how can I retrieve all tags that are associated with a specific user? I'm imagining something like Tag.objects.filter(owner=me), but of course that doesn't work.

For reference, here's the django-taggit documentation.

Raeleneraf answered 4/7, 2012 at 3:2 Comment(0)
S
21

I've came across a similar problem, and here is my solution:

tags = Tag.objects.filter(book__owner=me)
tags |= Tag.objects.filter(journalarticle__owner=me)
tags = tags.distinct()

hope it will help~

Sporulate answered 3/8, 2012 at 6:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.