4👍
✅
You can do it by using a function or lambda expression as the default:
class Bill(models.Model):
serial = models.IntegerField(default=lambda: Bill.objects.latest('id').serial + 1)
# ...
Basically, grab the latest model, and use its serial (plus one) as the default value. This will work if your serial is an integer, otherwise you’ll have to use your own logic. Also note that .latest() will raise DoesNotExist if you don’t have any bills in the database.
1👍
You can always use an AutoField
for this. As that link shows, the database will automatically increment it for you, but you can still set your own explicitly.
See the section a few lines down that’s called Explicitly specifying auto-primary-key values.
👤Ben
- [Django]-How to inject same context in many different Django views?
- [Django]-How to get the filename and line number of a Django template error when calling render()?
- [Django]-Django Package tests not found
- [Django]-Django. Get only current day. Only day without time
Source:stackexchange.com