Django Tag model design

azio picture azio · Nov 10, 2012 · Viewed 16.5k times · Source

I am wondering if the following is the correct way to create tagging system for images and being able to render a tag cloud:

from django.db import models

class Tag(models.Model):
    word        = models.CharField(max_length=35)
    slug        = models.CharField(max_length=250)
    created_at  = models.DateTimeField(auto_now_add=False)

    def __unicode__(self):
        return self.word

class Photo(models.Model):
    slug                = models.CharField(max_length=250)
    filename            = models.CharField(max_length=200)
    extension           = models.CharField(max_length=4)
    size                = models.IntegerField()
    ...
    tags                = models.ManyToManyField(Tag)

    def __unicode__(self):
        return self.slug

Note that my database table will include millions of rows and each image will have 4-8 tags.

Please advise.

Answer

Arion picture Arion · Nov 10, 2012

If all you want to do is create a tag cloud, than that data model should be sufficient. I would make one modification:

tags = models.ManyToManyField(Tag,related_name='photos')

That will make reverse lookups in you photo views cleaner to read and easier to remember.

However, I would consider other use cases for your tags. Is a tag cloud the only thing you want to use the tagging for? Is there any meta data that the relationship should contain?

If you're planning on having millions of rows, then caching is going to be as important as the data model.

Also, to avoid reinventing the wheel, see if anyone else has built a library that serves your purposes: http://www.djangopackages.com/grids/g/tagging/