Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 658
Joe Mornin Avatar asked Jul 04 '12 03:07

Joe Mornin


1 Answers

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~

like image 114
Flynn Avatar answered Oct 21 '22 18:10

Flynn