python get_or_create() 是否必须立即保存?(姜戈)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1095663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 21:28:31  来源:igfitidea点击:

Does get_or_create() have to save right away? (Django)

pythondjango

提问by rick

I need to use something like get_or_create() but the problem is that I have a lot of fields and I don't want to set defaults (which don't make sense anyway), and if I don't set defaults it returns an error, because it saves the object right away apparently.

我需要使用 get_or_create() 之类的东西,但问题是我有很多字段,我不想设置默认值(无论如何都没有意义),如果我不设置默认值,它会返回一个错误,因为它显然立即保存了对象。

I can set the fields to null=True, but I don't want null fields.

我可以将字段设置为 null=True,但我不想要空字段。

Is there any other method or any extra parameter that can be sent to get_or_create() so that it instantiates an object but doesn't save it until I call save() on it?

是否有任何其他方法或任何额外的参数可以发送到 get_or_create() 以便它实例化一个对象但在我调用 save() 之前不会保存它?

Thanks.

谢谢。

采纳答案by Noah Medling

You can just do:

你可以这样做:

try:
    obj = Model.objects.get(**kwargs)
except Model.DoesNotExist:
    obj = Model(**dict((k,v) for (k,v) in kwargs.items() if '__' not in k))

which is pretty much what get_or_createdoes, sans commit.

这几乎是什么get_or_create,没有提交。