Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8001391
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T16:04:55+00:00 2026-06-04T16:04:55+00:00

edit: To prevent everyone from reading too much: The problem is that i do

  • 0

edit:

To prevent everyone from reading too much: The problem is that i do not understand what

Q(tag_rep__tag=tag.id)

really does for this model:

class Item(models.Model):

    tag_rep=generic.GenericRelation(TaggedItem)

Most probably tag_rep__tag does return a list of tags, not a single tag. So i can’t just do the query like i did it. How can i compare tag_rep__tag to find out if it

  1. contains any of a list of tags
  2. contains all of a list of tags

I’m trying to build a queryset based tagfilter for items that have tagging tags. I allready succeeded with the creation of the filters, but they are based on pythons filter and return a list:

class TagFilter(object):

    def __init__(self,any_tags,avoid_tags,all_tags):
         # all tags as tag instances
         self.any_tags = any_tags
         self.avoid_tags = avoid_tags
         self.all_tags = all_tags

    def seek_any_tags(self, item):
        for tag in self.any_tags:
            if tag in item.tags:
               return True
        return False

    def items_with_any_tags(self,items):
        return filter(self.seek_any_tags,items)

This worked pretty well, but now i need a queryset in return to pass into a formset. So the current method is not working anymore, as it returns a list. To be able to access the tags of my model i did this:

from django.contrib.contenttypes import generic
from tagging.models import TaggedItem

class Item(models.Model):

    # some_fields here

    tag_rep = generic.GenericRelation(TaggedItem) 

The filter seek_any_tags was the only one i could allready rebuild in form of a database query. After reading some SO posts and doing a lot of googling i came up with this solution:

def seek_any_tags_qs(self,items):

    if self.any_tags!=None:
        q = reduce(lambda x, y: x | y, [Q(tag_rep__tag=tag.id) for tag in self.any_tags])
        items = items.filter(q)

    return items

Quite nice, and yes, i’m a bit proud about it. But now there are two more filters i want to build: avoid_any_tags and seek_all_tags. I tried to do them in the same way i did the seek_any_tags filter:

def avoid_any_tags_qs(self,items):

    if self.avoid_tags != None:
        q = reduce(lambda x, y: x | y, [Q(tag_rep__tag=tag.id) for tag in self.avoid_tags])
        items = items.exclude(q)

    return items


def seek_all_tags_qs(self,items):

    if self.all_tags != None:
        q = reduce(lambda x, y: x & y, [Q(_tags__contains=tag.name) for tag in self.seek_tags])
        items.filter(q)

    return items

avoid_any_tags should exclude every item that has any of the tags in avoid_tags. The last one, seek_all_tags, should only return items that have all of the tags in all_tags.

But avoid_any_tags doesn’t work as exected. It only excludes elements that have tags in avoid_tags and none else. If an item has any tag that is not in avoid_tags it is not excluded. Why not?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T16:04:57+00:00Added an answer on June 4, 2026 at 4:04 pm

    I don’t think this is a fully appropriate query (from your examples):

    Q(tag_rep__tag=tag.id)
    

    I am assuming you are following close to the examples listed here, and that the tag field of that TaggedItem is a slug (string) field? So right off the bat, filtering where the id is equal to the slugfield does not seem right. Also, you are correct that your GenericRelation represents a list (or a queryset for that matter). Its a reverse reference back to the TaggedItem specifying its foreignkey field. So you would be able to do: Item.tag_rep.all()

    There is so much extra information in your question that its a bit hard to follow, so I am just going to ignore most of that and address your summary at the top.

    # Any of a list of strings*
    any_tags = ['foo', 'bar']
    Item.objects.filter(tag_rep__tag__in=any_tags)
    

    As for the “has all tags in given tag list”, maybe there is a really complex django query based way to do this, but here is an approach with the intermediate steps being on the client side:

    # items having all tags in a given list of tags
    from collections import defaultdict
    
    tag_vals = Item.objects.all().values_list('id', 'tags__tag').distinct()
    # produces result like:  `[(1, u'bdfl'), (1, u'boom'), (2, u'bar'), ...)`
    
    all_tags = set(['boom', 'fizz'])
    
    tag_groups = defaultdict(set)
    for id_, tag in tag_vals:
        tag_groups[id_].add(tag)
    # produces tag_groups like `{1: set([u'fizz', u'foo', u'boom']), ...}`
    
    item_ids = [id_ for id_,tags in d.iteritems() if tags.issubset(all_tags)]
    Item.objects.filter(id__in=item_ids)
    

    In this last example, it would match situations where an Item has tags ['a,'b'] and the all_tags is ['a','b',c'], but it would not match situations where the Item has more tags than are in all_tags, but the ones it has do match. To have it match either way, you would have to modify that item_ids filter:

    item_ids = [id_ for id_,tags in d.iteritems() if \
                    tags.issubset(all_tags) or tags.issuperset(all_tags)]
    Item.objects.filter(id__in=item_ids)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

How do I prevent my .net (C#) program from ever writing to disk? Edit:
Edit 2: It seems clear that no one seems to be able to understand
Visual Studio 2008 does a much better job of detecting and adding controls from
How can i prevent a partial view from being loaded by typing http://mydomain.com/site/edit/1 Is
I want to prevent automated html scraping from one of our sites while not
EDIT 1 I apologize but after reading the 2 suggested articles I still don't
Is it possible to prevent a user from editing the title of a node
So I want to prevent people from copying files out of my app while
Edit : What I really need to know is if there is any javascript
I understand that the proper structure for separation-of-concerns in MVC is to have view-models

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.