Created
June 23, 2011 00:21
-
-
Save copitux/1041620 to your computer and use it in GitHub Desktop.
Type with models inheritance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
##### Test ... | |
# | |
# DocumentService(name='document1').save() | |
# VideoService(name='video1').save() | |
# DocumentService(name='document2').save() | |
# VideoService(name='video2').save() | |
# | |
# DocumentService.objects.all() | |
#> [<DocumentService: <class 'test_app.models.DocumentService'>: document1>, <DocumentService: <class 'test_app.models.DocumentService'>: document2>] | |
# | |
# VideoService.objects.all() | |
#> [<VideoService: <class 'test_app.models.VideoService'>: video1>, <VideoService: <class 'test_app.models.VideoService'>: video2>] | |
# | |
# Service.objects.all() | |
#> [<DocumentService: <class 'test_app.models.DocumentService'>: document1>, <VideoService: <class 'test_app.models.VideoService'>: video1>, <DocumentService: <class 'test_app.models.DocumentService'>: document2>, <VideoService: <class 'test_app.models.VideoService'>: video2>] | |
from django.db import models | |
from django.contrib.contenttypes.models import ContentType | |
from test_app.manager import TypeFilter | |
class ServiceMetaclass(models.base.ModelBase): | |
def __call__(cls, *args, **kwargs): | |
obj = super(ServiceMetaclass, cls).__call__(*args, **kwargs) | |
return obj.get_object(cls) | |
class Service(models.Model): | |
__metaclass__ = ServiceMetaclass | |
name = models.CharField(max_length=25) | |
age = models.CharField(max_length=25) | |
#todo: choices with querys ContentTypes for admin work | |
content_type = models.ForeignKey(ContentType) | |
objects = models.Manager() | |
objects_typed = TypeFilter() | |
def __unicode__(self): | |
return '{cls}: {name}'.format(cls=self.__class__, name=self.name) | |
def save(self, *args, **kwargs): | |
self.content_type = ContentType.objects.get_for_model(self) | |
super(Service, self).save(*args, **kwargs) | |
def get_object(self, unr_class): | |
#object not saved, let it continue | |
if self.id is None: | |
return self | |
#try instance Service when isn't (Service.objets.all()) | |
if self.__class__ != self.content_type.model_class(): | |
return self.content_type.model_class().objects.get(pk=self.pk) | |
#try instance Service childs (DocumentService.objects.all()) | |
else: | |
return self | |
class DocumentService(Service): | |
def hi(self): | |
print 'i am document service' | |
class VideoService(Service): | |
def hi(self): | |
print 'i am video service' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment