[Django]-Django model class methods for predefined values

51๐Ÿ‘

โœ…

You should perhaps implement this by defining a custom manager for your class, and adding two manager methods on that manager (which I believe is the preferred way for adding table-level functionality for any model). However, another way of doing it is by throwing in two class methods on your class that query and return resulting objects, such as:

class Status(models.Model):
    code = models.IntegerField()
    text = models.CharField(maxlength=255)

    @classmethod
    def successful(cls):
        return cls.objects.get(code=0)

    @classmethod
    def failed(cls):
        return cls.objects.get(code=1)

Do note please that get() is likely to throw different exceptions, such as Status.DoesNotExist and MultipleObjectsReturned.

And for an example implementation of how to do the same thing using Django managers, you could do something like this:

class StatusManager(models.Manager):
    def successful(self):
        return self.get(code=1)

    def failed(self):
        return self.get(code=0)

class Status(models.Model):
    code = models.IntegerField()
    text = models.CharField(maxlength=255)

    objects = StatusManager()

Where, you could do Status.objects.successful() and Status.objects.failed() to get what you desire.

๐Ÿ‘คayaz

Leave a comment