Saturday, April 15, 2017

Generic relations in Django

While using django's content management system (admin), for adding different objects on it, you may want things like audit notes, that can be used for reference in the future or get some more info. you have two choice -

  1. Add a explicit field to the object, though the down side is you will need to add that extra field with all the objects where you want note.
  2. Create a generic model which can be used with different objects in your app. 

It's no brainer between above two choice, answer is 2nd. Generic relations are at help.

You can checkout django-contrib-comments, it's one of the example of generic relations. Let's take example of how Notes like foreign key reference can be added freely to any model in your app.

from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType

class Note(models.Model):
    note = models.TextField("note",
    date = models.DateTimeField(auto_now_add=True)
    # Below the mandatory fields for generic relation
    content_type = models.ForeignKey(
        ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

    class Meta:
        verbose_name = 'Staff Note'

    def __unicode__(self):
        return"%B %d, %Y")

Now, this Notes object can be referenced with any other model you want to use it with. Here is one example -

from django.contrib.contenttypes.fields import GenericRelation
from notes.models import Note

class MyModel(models.Model):
    name = models.CharField("Name", max_length=100)
    notes = GenericRelation(Note)

When you run migration, it doesn't add anything in MyModel, as its generic relation it gets its references via django content type and object id.

How to add it in admin?

from django.contrib.contenttypes.admin import GenericTabularInline
from .models import Note

class NoteInline(GenericTabularInline):
    model = Note
    extra = 0

from misc.admin import NoteInline
from .models import MyModel

class MyModelAdmin(admin.ModelAdmin):
    inlines = [NoteInline, ], MyModelAdmin)

And you are all set. It's easy to plug, efficient, and clean implementation. Good luck!

No comments:

Post a Comment