OpenSlides/openslides/utils/models.py

42 lines
1.3 KiB
Python
Raw Normal View History

2015-06-29 12:08:15 +02:00
from django.core.urlresolvers import reverse
from django.db import models
class MinMaxIntegerField(models.IntegerField):
2013-09-25 12:53:44 +02:00
"""
IntegerField with options to set a min- and a max-value.
"""
def __init__(self, min_value=None, max_value=None, *args, **kwargs):
self.min_value, self.max_value = min_value, max_value
super(MinMaxIntegerField, self).__init__(*args, **kwargs)
def formfield(self, **kwargs):
defaults = {'min_value': self.min_value, 'max_value': self.max_value}
defaults.update(kwargs)
return super(MinMaxIntegerField, self).formfield(**defaults)
2015-06-29 12:08:15 +02:00
class RESTModelMixin:
"""
Mixin for django models which are used in our rest api.
"""
def get_root_rest_element(self):
"""
Returns the root rest instance.
Uses self as default.
"""
return self
def get_root_rest_url(self):
"""
Returns the detail url of the root model of this object.
"""
# Gets the default url-name in the same way as django rest framework
# does in relations.HyperlinkedModelSerializer
root_instance = self.get_root_rest_element()
rest_url = '%s-detail' % type(root_instance)._meta.object_name.lower()
return reverse(rest_url, args=[str(root_instance.pk)])