Hi all,

There had been a discussion on selecting objects based on their tags in
a blogging application:
http://groups-beta.google.com/group/django-users/browse_thread/thread/f2bfff678b1f5ee8/

I want to do something similar, but a little bit more complicated. I am
trying to decide which entry to show based on the title and the tags of
the entries in a wiki-like application.

Say we have a model like:

class Tag(models.Model):
   tag     = models.CharField(maxlength = 50)

class Post(models.Model):
   title   = models.CharField(maxlength = 50)
   tags    = models.ManyToManyField(Tag)

Suppose we have a number of different entries for the title "blue" with
different tags (ie.: "blue:color", "blue: movie", "blue:hotel",
"blue:(hotel, London)" , "blue:(hotel, Amsterdam)", etc...

Suppose we have configured our urls.py so that we have the first part
of the url as the title and the rest as an array of tags, so that the
request /blue/hotel is translated as title = 'blue', tags = ('hotel',),
where /blue/hotel/London is title = 'blue', tags = ('hotel', 'London')

I want the request /blue/hotel/ to map to the entry for title="blue" &
tag="hotel", but *not* title = "blue" & tag = ('hotel', 'London'),
because, although the second one also satisfies the tag condition, the
first one satisfies the tag condition with least number of tags,
therefore it is more likely to be the desired content. The first will
be regarded as the exact match, and the second will be in the set of
related matches.

I have achieved this with a single SQL query like that:

SELECT tag.post_id, COUNT(*) c, SUM(tag.tag IN ('hotel', 'London') s
FROM post LEFT JOIN tag_post ON post.id = tag_post.post_id
WHERE post.title = 'blue'
GROUP BY post.id
HAVING s = 2
ORDER BY c
LIMIT 1

The 2 in "HAVING s = 2" is the number of tags to match.

Is there a more django style approach to achieve this.

Also, this model requires to define the title and tags as unique
together. But apparently:

class Post(models.Model):
   title   = models.CharField(maxlength = 50)
   tags    = models.ManyToManyField(Tag)
   class Meta:
       unique_together(('title', 'tags'),)

is not a valid definition. Is a model level definition is possible or
should this be managed at the application level?


Thanks for your time,
oMat


--~--~---------~--~----~------------~-------~--~----~
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?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to