Django raw ID fields - explained (basically)

Monday, September 22nd, 2008

Jump to Comments

Raw ID fields seem to be a really cool django feature that allows you to link one model into another and provide a pretty nice UI tool that allows your users (editorial) to select which model to include. Unfortunately a quick Google seems to return API docs (which for thicko’s like me are fairly difficult to understand).

Thankfully after using them in my day job I’m happy to say that they are actually a piece of cake to do - and I’m going to explain how (at least how I did them).

Django makes it really easy to insert a foreign key relationship between models. All you need do is use the native ForeignKey field type into your models.py. For example:


#you need to import the model you want to ForeignKey into of course
from django.contrib.sites.models import RossLikes

class Ross(models.Model):
    name = models.CharField(max_length-512)
    description = models.TextField()
    image = models.ImageField(upload_to='images')
    likes = models.ForeignKey(RossLikes)

This will provide you with an interface like below.

Django admin with the standard foreign key display (a big select box with ALL possible values)

It’s got all you need in there and can select any individual record in the RossLikes model to include alongside Ross. Thinking that you have a large number of things to pick from this kind of interface will quickly become a PITA. This is where raw ID fields come into play!

All you need to do it include this one line into your models modelAdmin method in admin.py:


class RossAdmin(admin.ModelAdmin):
    raw_id_fields = ('likes')

You’ll now get a nice picker style widget that provides you with all the values you had before in the select box with the extra win of being able to filter, search (whatever options you provide for the linked in model when you access it on it’s own!)

When raw ID\'s are set up you get a picker link which opens up a filtered view of the linked model. Pick anything you like (and find it easier)

I find this very helpful and I reckon you will to!