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
- Add Toggle Switch Widget to Django Forms by OgliariNatan 1 month, 4 weeks ago
 - get_object_or_none by azwdevops 5 months, 2 weeks ago
 - Mask sensitive data from logger by agusmakmun 7 months, 2 weeks ago
 - Template tag - list punctuation for a list of items by shapiromatron 1 year, 9 months ago
 - JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 1 year, 9 months ago
 
Comments
Please login first before commenting.