[Update: Changed question title to be more specific]
Sorry if I didn't make the question very well, I can't figure how to do this:
class WhatEver(): number = model.IntegerField('Just a Field', default=callablefunction) ...
callablefunction does this query:
from myproject.app.models import WhatEver def callablefunction(): no = WhatEver.objects.count() return no + 1
I want to automatically write the next number, and I don't know how to do it.
I have errors from
callablefunction stating that it cannot import the model, and I think there must be an easier way to do this. There's no need even to use this, but I can't figure how to do it with the pk number.
I've googled about this and the only thing I found was to use the save() method for auto incrementing the number... but I wanted to show it in the
<textfield> before saving...
What would you do?
Got it! I hope this will help everyone that has any problems making a auto-filled and auto-incrementing field in django. The solution is:
class Cliente(models.Model): """This is the client data model, it holds all client information. This docstring has to be improved.""" def number(): no = Cliente.objects.count() if no == None: return 1 else: return no + 1 clientcode = models.IntegerField(_('Code'), max_length=6, unique=True, \ default=number) [... here goes the rest of your model ...]
Take in care:
numberfunction doesn't take any arguments (not even self)
This function will automatically fill the
clientcode field with the next number (i.e. If you have 132 clients, when you add the next one the field will be filled with
clientcode number 133)
I know that this is absurd for most of the practical situations, since the PK number is also auto-incrementing, but there's no way to autofill or take a practical use for it inside the django admin.
[update: as I stated in my comment, there's a way to use the primary key for this, but it will not fill the field before saving]