On 5/18/06, Malcolm Tredinnick <[EMAIL PROTECTED]> wrote:
[...]

I was helped by Malcom on IRC, so the only decent thing to do, is to
post the solution here.

I'll try to explain as well as I understand it.
First some code:

class Tags(models.Model):

    tag = models.CharField(maxlength = 50)

    def __str__(self):

        return self.tag

class TagManager(models.Manager):

    def from_tags(self, tag_list):
        
        id_list = [int(t.id) for t in Tags.objects.filter(tag__in = tag_list)]

        all = Contract.objects.extra(tables = ['contracts_tags'], where =
[('contracts_tags.contract_id = contracts.id'), ('(SELECT COUNT(*)
FROM contracts_tags AS t WHERE t.tags_id IN (%s) AND t.contract_id =
contracts.id) = %d' % (','.join([str(tag) for tag in id_list]),
len(id_list)))]).distinct()

        return all

class Contract(models.Model):

    # Basic things

    file = models.FileField()
    name = models.CharField(maxlength = 200)
    update = models.DateTimeField('date uploaded')
    description = models.TextField()

    objects = TagManager()

    # These are used for indexing

    excerpt = models.TextField()
    tags = models.ManyToManyField(Tags)

You can call it like this:

tags = ["foo","bar"]

all = Contract.objects.from_tags(tags)

What happens is that you count how many tags match on each contract
ID. Since you only pick out the relevant tags, the count will equal
len(tags), if there's a match. This allows you to search for records
where there's only specific relations, when data is divided across
tables, in this case with a ManyToManyField().

It works fairly well and fast on my somewhat limited set of set, but I
think this would scale fine on a larger scale as well.

Thanks malcom!

-- 
Jesper Nøhr, Information Systems Developer, Opera Software
tel: +47-24164348 / cell: +47-46056753 / [EMAIL PROTECTED]

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users
-~----------~----~----~----~------~----~------~--~---

Reply via email to