覆盖 Django get_or_create
我有一个模型,我覆盖了 save
方法,以便 save
方法可以传入一些数据并在保存之前自动填充字段。这是我的模型:
class AccountModel(models.Model):
account = models.ForeignKey(Account)
def save(self, request=None, *args, **kwargs):
if request:
self.account = request.session['account']
super(AccountModel, self).save(*args, **kwargs)
class Meta:
abstract = True
我的想法是为需要与帐户关联的对象建立一个基本模型,然后我就不必在每次出现帐户连接时处理它们(这是很多)。
但是:我还想使用 get_or_create ,它可以保存新对象而不传入请求。我知道不使用 get_or_create
并执行 try
/except
是可行的,但我想知道是否存在是一种覆盖 get_or_create
的方法,正确的方法是什么。
我查看了 Manager 的代码(我正在查看其重写),并且 get_or_create 函数仅调用 QuerySet.get_or_create 函数。也许我可以编写它来使用其他管理器函数,而不是 get_or_create
的 QuerySet
版本? 大家觉得怎么样?
I have a model that I overrode the save
method for, so that the save
method can be passed in some data and auto-fill-in a field before saving. Here is my model:
class AccountModel(models.Model):
account = models.ForeignKey(Account)
def save(self, request=None, *args, **kwargs):
if request:
self.account = request.session['account']
super(AccountModel, self).save(*args, **kwargs)
class Meta:
abstract = True
The idea is I set up a base model for objects that need to be associated with an account and then I won't have to deal with the account connections every time they come up (which is a lot).
But: I'd also like to use get_or_create
, which saves the new objects without passing in the request. I know it is doable to not use get_or_create
and do a try
/except
instead, but I'd like to know if there is a way to override get_or_create
and what is the proper way to do it.
I looked at the code for the Manager
(which I am looking at overriding) and the get_or_create
function just calls a QuerySet.get_or_create
function. Maybe I can write it to use other manager functions and not the QuerySet
version of get_or_create
?
What do y'all think?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以子类化 django.db.models.query.QuerySet 并重写其中的 get_or_create 方法以接受您的 request 关键字参数并将其传递给 <我猜是 code>save ,但它不是很漂亮。
然后,您可以将自定义管理器添加到使用此自定义
QuerySet
的Account
模型:然后在您的模型中使用此管理器:
但是您可能会发现
try- except
方法毕竟更简洁:)You could subclass
django.db.models.query.QuerySet
and override theget_or_create
method there to accept yourrequest
keyword argument and pass it ontosave
I guess, but it isn't very pretty.You could then add a custom manager to your
Account
model which uses this customQuerySet
:Then use this manager in your model:
But you might find that the
try-except
method is neater after all :)