Getting a new ID according to the content type.
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 43 44 45 46 47 48 49 50 51 | # models.py
from django.db import models
from django.contrib.contenttypes.models import ContentType
""" Managers """
class LastIdentifierManager(models.Manager):
def get_new_id(self, obj):
"""
Getting a new ID according to the content type.
It retrieves the last saved value and adds 1.
then, this new value is saved and returned.
"""
if isinstance(obj, models.base.ModelBase):
content_type = ContentType.objects.get_for_model(obj)
else:
content_type = obj
lastidentifier, created = self.get_or_create(content_type=content_type)
lastidentifier.value += 1
lastidentifier.save()
return lastidentifier.value
"""Model"""
class LastIdentifier(models.Model):
value = models.IntegerField('last ID', default=0)
content_type = models.ForeignKey(ContentType, verbose_name='content type', unique=True)
objects = LastIdentifierManager()
class Meta:
verbose_name = 'last ID'
verbose_name_plural = 'last IDs'
def __unicode__(self):
return "%s - %s" % (self.value, self.content_type)
# views.py - sample view
from apps.foo.models import Foo
from apps.foo.models import LastIdentifier
from django.http import HttpResponse
def identifier(request):
ref = LastIdentifier.objects.get_new_id(Foo)
return HttpResponse(ref)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.