1 from django.db.models import Q
 
   2 from catalogue.models import Book, Tag
 
   3 from catalogue import utils
 
   4 from catalogue.tasks import touch_tag
 
   5 from social.models import Cite
 
   9     return user.is_authenticated() and work.tags.filter(category='set', user=user).exists()
 
  12 def get_set(user, name):
 
  13     """Returns a tag for use by the user. Creates it, if necessary."""
 
  15         tag = Tag.objects.get(category='set', user=user, name=name)
 
  16     except Tag.DoesNotExist:
 
  17         tag = Tag.objects.create(category='set', user=user, name=name,
 
  18                 slug=utils.get_random_hash(name), sort_key=name.lower())
 
  22 def set_sets(user, work, sets):
 
  23     """Set tags used for given work by a given user."""
 
  25     old_sets = list(work.tags.filter(category='set', user=user))
 
  27     work.tags = sets + list(
 
  28             work.tags.filter(~Q(category='set') | ~Q(user=user)))
 
  30     for shelf in [shelf for shelf in old_sets if shelf not in sets]:
 
  32     for shelf in [shelf for shelf in sets if shelf not in old_sets]:
 
  36     Tag.objects.filter(category='set', user=user, book_count=0).delete()
 
  39 def cites_for_tags(tags):
 
  40     """Returns a QuerySet with all Cites for books with given tags."""
 
  41     books = Book.tagged.with_all(tags).order_by().values_list('id', flat=True)
 
  43     return Cite.objects.filter(book__id__in=books)