Login

Getting a new ID according to the content type

Author:
rodnsi
Posted:
May 19, 2009
Language:
Python
Version:
1.0
Tags:
django models model id
Score:
1 (after 1 ratings)

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

  1. Automating URLs by jorjun 5 years, 11 months ago
  2. Generic Model by hakejam 8 years, 2 months ago
  3. Child aware model inheritance by rix 6 years, 6 months ago
  4. Manager method for limiting GenericForeignKey queries by zerok 6 years, 9 months ago
  5. BigIntegerField and BigAutoField by fnl 6 years, 5 months ago

Comments

Please login first before commenting.