Django一次保存并返回对象(带有自定义pk) [英] Django save and return object at once (with a custom pk)

查看:66
本文介绍了Django一次保存并返回对象(带有自定义pk)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用自定义创建方法 create_actor 创建模型的对象,如下所示:

  Class ActorsManager(models.QuerySet):def create_actor(自我,电子邮件,演员型locationid,主电话,actoruniversalid):演员= self.model(email = email,actortype =演员类型,locationid = locationid,primaryphone =主电话,actoruniversalid = actoruniversalid)actor.save(using ='gpr')回归演员actor_entry = Actors.objects.using('gpr').create_actor(电子邮件='',actortype = 1,locationid = location_entry,primaryphone ='',actoruniversalid = new_bluenumber) 

我没有在 actor_entry 变量中获得最近创建的对象,可能是我做错了,请帮忙.

我正在使用插入前 SQL触发器在数据库中将uuid生成为pk(此处为CharField),因此该对象在保存之前确实有一个pk(由数据库生成)./p>

演员模型

  class Actors(models.Model):actorid = models.CharField(db_column ='ActorID',primary_key = True,max_length = 255)#字段名称变为小写.actoruniversalid = models.CharField(db_column ='ActorBluenumber',unique = True,blank = True,null = True,max_length = 254)............objects = ActorsManager.as_manager()类Meta:管理=假db_table ='演员' 

解决方案

正如@knbk指出,只有AutoField才能将pk设置为对象,因此用于检索pk的 pythonic 逻辑是如果不是AutoField,则不会执行,因此django对此一无所知.

搜索django文档后,我找到了AutoField的UUID替代品,一个 解决方案

As @knbk pointed out that only an AutoField can set the pk to an object and so the pythonic logic to retrieve the pk is not executed when its not an AutoField and so django doesn't know about it.

After searching the django documentation I found an alternative to AutoField for UUIDs,an UUIDField which is best suited for my Use Case.

actorid = models.UUIDField(db_column='ActorID', primary_key=True, editable=False, default=uuid.uuid4)

So now the django does know of the pk and thus the object is retrieved after being saved.

Thank you all for the help.

这篇关于Django一次保存并返回对象(带有自定义pk)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆