Auto filling polymorphic table on save or on delete in django
Posted
by
Mo J. Mughrabi
on Stack Overflow
See other posts from Stack Overflow
or by Mo J. Mughrabi
Published on 2010-12-25T12:40:21Z
Indexed on
2010/12/25
12:54 UTC
Read the original article
Hit count: 286
Hi, Am working on an project in which I made an app "core" it will contain some of the reused models across my projects, most of those are polymorphic models (Generic content types) and will be linked to different models.
Example below am trying to create audit model and will be linked to several models which may require auditing.
This is the polls/models.py
from django.db import models
from django.contrib.auth.models import User
from core.models import *
from django.contrib.contenttypes import generic
class Poll(models.Model):
## TODO: Document
question = models.CharField(max_length=300)
question_slug=models.SlugField(editable=False)
start_poll_at = models.DateTimeField(null=True)
end_poll_at = models.DateTimeField(null=True)
is_active = models.BooleanField(default=True)
audit_obj=generic.GenericRelation(Audit)
def __unicode__(self):
return self.question
class Choice(models.Model):
## TODO: Document
choice = models.CharField(max_length=200)
poll=models.ForeignKey(Poll)
audit_obj=generic.GenericRelation(Audit)
class Vote(models.Model):
## TODO: Document
choice=models.ForeignKey(Choice)
Ip_Address=models.IPAddressField(editable=False)
vote_at=models.DateTimeField("Vote at", editable=False)
here is the core/modes.py
from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
class Audit(models.Model):
## TODO: Document
# Polymorphic model using generic relation through DJANGO content type
created_at = models.DateTimeField("Created at", auto_now_add=True)
created_by = models.ForeignKey(User, db_column="created_by", related_name="%(app_label)s_%(class)s_y+")
updated_at = models.DateTimeField("Updated at", auto_now=True)
updated_by = models.ForeignKey(User, db_column="updated_by", null=True, blank=True,
related_name="%(app_label)s_%(class)s_y+")
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField(unique=True)
content_object = generic.GenericForeignKey('content_type', 'object_id')
and here is polls/admin.py
from django.core.context_processors import request
from polls.models import Poll, Choice
from core.models import *
from django.contrib import admin
class ChoiceInline(admin.StackedInline):
model = Choice
extra = 3
class PollAdmin(admin.ModelAdmin):
inlines = [ChoiceInline]
admin.site.register(Poll, PollAdmin)
Am quite new to django, what am trying to do here, insert a record in audit when a record is inserted in polls and then update that same record when a record is updated in polls.
© Stack Overflow or respective owner