Login

Make tags easier with properties

Author:
ubernostrum
Posted:
March 6, 2007
Language:
Python
Version:
Pre .96
Score:
25 (after 31 ratings)

Jonathan Buchanan's Django tagging application is the best thing since sliced bread, and makes adding generic tagging to any model trivially easy. But you can make it just a tiny bit easier to use by setting up a property on your model for handling the tags.

Once you've set this up, you can access and set tags in a fairly natural way:

>>> obj = MyModel.objects.get(pk=1)
>>> obj.tags = 'foo bar'
>>> obj.tags
[<Tag: foo>, <Tag: bar>]

And remember that obj.tags will return a QuerySet, so you can do filtering on it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
from django.db import models
from tagging.models import Tag

class MyModel(models.Model):
    name = models.CharField(maxlength=250)
    tag_list = models.CharField(maxlength=250)
    
    def save(self):
        super(MyModel, self).save()
        self.tags = self.tag_list
    
    def _get_tags(self):
        return Tag.objects.get_for_object(self)
    
    def _set_tags(self, tag_list):
        Tag.objects.update_tags(self, tag_list)
    
    tags = property(_get_tags, _set_tags)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 8 months, 3 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 9 months ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 3 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 4 months ago
  5. Help text hyperlinks by sa2812 1 year, 5 months ago

Comments

jacobian (on March 6, 2007):

Clever clever :)

There's likely an easy way to encapsulate this into a descriptor so you could just do:

tags = TagField()

and have everything work like you said. I should experiment with that...

#

zeeg (on March 6, 2007):

We actually do something similar to this as well, it's quite handy. The only difference is for our get tags and set tags methods we validate the data to make sure we can't simply skip a query.

#

ubernostrum (on August 25, 2007):

It's worth noting that Jonathan has now added a TagField to django-tagging, which uses a descriptor to get/set the tags. That offers a similar interface to this, but wraps it up with admin-interface goodness :)

#

ymxiao (on September 24, 2011):

good job i'm newbie in python, thinks for introduce property to me.

#

Please login first before commenting.