diff options
author | 2018-09-21 22:43:52 +0200 | |
---|---|---|
committer | 2018-09-21 22:43:52 +0200 | |
commit | b0538bd2191b99eac1ee5ae7e95d0875dd71d181 (patch) | |
tree | c51994c8a075a28b2ceacc1556b4018f9246b752 /api | |
parent | Add help texts on all API models. (diff) |
Add `__repr__` to all models.
Diffstat (limited to 'api')
-rw-r--r-- | api/models.py | 31 | ||||
-rw-r--r-- | api/tests/test_models.py | 17 |
2 files changed, 43 insertions, 5 deletions
diff --git a/api/models.py b/api/models.py index f2e47108..c04984fa 100644 --- a/api/models.py +++ b/api/models.py @@ -1,8 +1,29 @@ +from operator import itemgetter + from django.core.validators import MaxValueValidator, MinValueValidator, RegexValidator from django.db import models -class DocumentationLink(models.Model): +class ModelReprMixin: + """ + Adds a `__repr__` method to the model subclassing this + mixin which will display the model's class name along + with all parameters used to construct the object. + """ + + def __repr__(self): + attributes = ' '.join( + f'{attribute}={value!r}' + for attribute, value in sorted( + self.__dict__.items(), + key=itemgetter(0) + ) + if not attribute.startswith('_') + ) + return f'<{self.__class__.__name__}({attributes})>' + + +class DocumentationLink(ModelReprMixin, models.Model): """A documentation link used by the `!docs` command of the bot.""" package = models.CharField( @@ -21,7 +42,7 @@ class DocumentationLink(models.Model): ) -class OffTopicChannelName(models.Model): +class OffTopicChannelName(ModelReprMixin, models.Model): name = models.CharField( primary_key=True, max_length=96, @@ -30,7 +51,7 @@ class OffTopicChannelName(models.Model): ) -class SnakeName(models.Model): +class SnakeName(ModelReprMixin, models.Model): """A snake name used by the bot's snake cog.""" name = models.CharField( @@ -44,7 +65,7 @@ class SnakeName(models.Model): ) -class Role(models.Model): +class Role(ModelReprMixin, models.Model): """A role on our Discord server.""" id = models.BigIntegerField( # noqa @@ -85,7 +106,7 @@ class Role(models.Model): ) -class Member(models.Model): +class Member(ModelReprMixin, models.Model): """A member of our Discord server.""" id = models.BigIntegerField( # noqa diff --git a/api/tests/test_models.py b/api/tests/test_models.py new file mode 100644 index 00000000..7ed49a78 --- /dev/null +++ b/api/tests/test_models.py @@ -0,0 +1,17 @@ +from django.test import SimpleTestCase + +from ..models import ModelReprMixin + + +class SimpleClass(ModelReprMixin): + def __init__(self, is_what): + self.the_cake = is_what + + +class ReprMixinTests(SimpleTestCase): + def setUp(self): + self.klass = SimpleClass('is a lie') + + def test_shows_attributes(self): + expected = "<SimpleClass(the_cake='is a lie')>" + self.assertEqual(repr(self.klass), expected) |