3

Cool New django-taggit API

 3 years ago
source link: https://alexgaynor.net/2010/may/04/cool-new-django-taggit-api/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Cool New django-taggit API · Alex Gaynor

Alex Gaynor

Hi, I'm Alex. I've been CISO at a startup named Alloy, an engineer working on Firefox security, and before that at the U.S. Digital Service. I'm an avid open source contributor and live in Washington, DC.

© 2020. All rights reserved.

Cool New django-taggit API

Tue, May 4, 2010

A little while ago I wrote about some of the issues with the reusable application paradigm in Django. Yesterday Carl Meyer pinged me about an issue in django-taggit, it uses an IntegerField for the GenericForeignKey, which is great. Except for when you have a model with a CharField, TextField, or anything else for a primary key. The easy solution is to change the GenericForeignKey to be something else. But that’s lame, a pain in the ass, and a hack (more of a hack than a GenericForeignKey in the first place).

The alternate solution we came up with:

from django.db import models

from taggit.managers import TaggableManager
from taggit.models import TaggedItemBase


class TaggedFood(TaggedItemBase):
    content_object = models.ForeignKey('Food')

class Food(models.Model):
    # ... fields here

    tags = TaggableManager(through=TaggedFood)

Custom through models for the taggable relationship! This let’s the included GenericForeignKey implementation cater to the common case of integer primary keys, and lets other people provide their own implementations when necessary. Plus it means doing things like, adding a ForeignKey to auth.User or adding the “originally” typed version of the tag (for systems where tags are normalized).

In addition I’ve finally added some docs, they aren’t really complete, but they’re a start. I’m planning a release for sometime next week, unless some major issue pops up.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK