Skip to content

Commit

Permalink
Added nullable generic object mixin. Added method to the generic object
Browse files Browse the repository at this point in the history
manager.
  • Loading branch information
troygrosfield committed Apr 26, 2016
1 parent cccbaa6 commit 52b8093
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 5 deletions.
40 changes: 35 additions & 5 deletions django_core/db/models/managers.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,18 +236,48 @@ def get_by_user_id(self, user_id, **kwargs):


class GenericManager(models.Manager):
"""Model manager for models that have generic objects."""

def get_or_create_generic(self, content_object, **kwargs):
def create_generic(self, content_object=None, **kwargs):
"""Create a generic object.
:param content_object: the content object to create a new object for.
"""
if content_object:
kwargs['content_type'] = ContentType.objects.get_for_model(
content_object
)
kwargs['object_id'] = content_object.id

return self.create(**kwargs)

def filter_generic(self, content_object=None, **kwargs):
"""Filter by a generic object.
:param content_object: the content object to filter on.
"""
if content_object:
kwargs['content_type'] = ContentType.objects.get_for_model(
content_object
)
kwargs['object_id'] = content_object.id

return self.filter(**kwargs)

def get_or_create_generic(self, content_object=None, **kwargs):
"""Gets or creates a generic object. This is a wrapper for
get_or_create(...) when you need to get or create a generic object.
:param obj: the object to get or create
:param kwargs: any other kwargs that the model accepts.
"""
content_type = ContentType.objects.get_for_model(content_object)
return self.get_or_create(content_type=content_type,
object_id=content_object.id,
**kwargs)
if content_object:
kwargs['content_type'] = ContentType.objects.get_for_model(
content_object
)
kwargs['object_id'] = content_object.id

return self.get_or_create(**kwargs)

def get_by_content_type(self, content_type):
"""Gets all objects by a content type."""
Expand Down
14 changes: 14 additions & 0 deletions django_core/db/models/mixins/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,17 @@ class Meta:
object_id = models.PositiveIntegerField(db_index=True, unique=False)
content_object = GenericForeignKey('content_type', 'object_id')
objects = GenericManager()


class AbstractNullableGenericObject(models.Model):
"""Abstract model class for a generic object that's optional."""

class Meta:
abstract = True

content_type = models.ForeignKey('contenttypes.ContentType', blank=True,
null=True, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField(db_index=True, unique=False,
blank=True, null=True)
content_object = GenericForeignKey('content_type', 'object_id')
objects = GenericManager()

0 comments on commit 52b8093

Please sign in to comment.