Django - How to get self.id when saving a new object?

人走茶凉 提交于 2019-11-28 09:37:49

If it's a new object, you need to save it first and then access self.id, because

"There's no way to tell what the value of an ID will be before you call save(), 
 because that value is calculated by your database, not by Django."

Check django's document https://docs.djangoproject.com/en/dev/ref/models/instances/

You might need to save this file/instance twice:

You can use a post_save signal on the model that looks for the created flag, and re-saves the instance updating the url (and moving/renaming the file as necessary), since the instance will now have an ID. Make sure you only do this conditioned on created, though, otherwise you will continuously loop in saving: saving kicks off a post-save signal, which does a save, which kicks off a post-save signal...

See https://docs.djangoproject.com/en/dev/ref/signals/#post-save

Chandan Maruthi

Note: You need to have the models.AutoField(primary_key=True) attribute set, otherwise the database will be updated with a new id but Django will not recognize it.

models.AutoField(primary_key=True)

I know this is an old one but I thought this might be of use to someone, seems to work OK so far.

Views.py

    #Queries model and appends id's to list
    try:
        qs = YourModel.objects.all()
        qslist = []

        for item in qs:
            qslist.append(item.id)

        newid = int(max(qslist) + 1)
    #If no entries are found, assume this is the first entry.
    except:
        newid = 1

However, Im not sure how well this will perform on large DBs.

  q = Order.objects.values_list('id', flat=True).order_by('-id')[:1]
            if len(q):
                self.number = str(self.id) if self.id else str(int(q.get()) + 1)
            else:
                self.number = 1
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!