Login

Content type to get Model

Author:
agusmakmun
Posted:
January 14, 2018
Language:
Python
Version:
Not specified
Tags:
django contenttypes content-type django-models
Score:
0 (after 0 ratings)

Instance class model with class ModelName(models.Model, ContentTypeToGetModel):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class ContentTypeToGetModel(object):

    """
    requires fields:
        - content_type: FK(ContentType)
        - object_id: PositiveIntegerField()
    """

    def get_related_object(self):
        """
        return the related object of content_type.
        eg: <Question: Holisticly grow synergistic best practices>
        """
        # This should return an error: MultipleObjectsReturned
        # return self.content_type.get_object_for_this_type()
        # So, i handle it with this one:
        model_class = self.content_type.model_class()
        return model_class.objects.get(id=self.object_id)

    @property
    def _model_name(self):
        """
        return lowercase of model name.
        eg: `question`, `answer`
        """
        return self.get_related_object()._meta.model_name

"""
# USAGE EXAMPLE

class Flag(TimeStampedModel, ContentTypeToGetModel):
    creator = models.ForeignKey(
        User, related_name='flag_creator')

    content_type = models.ForeignKey(
        ContentType, related_name='flags',
        on_delete=models.CASCADE)

    object_id = models.PositiveIntegerField(_('Object id'))

    content_object = GenericForeignKey('content_type', 'object_id')
"""

More like this

Comments

Please login first before commenting.