Django:如何从管理器内部访问模型的实例?
class SupercalifragilisticexpialidociousManager(models.Manager):
# Sorry, I'm sick of Foo and Spam for now.
def get_query_set(self, account=None):
return super(SupercalifragilisticexpialidociousManager,
self).get_query_set().filter(uncle=model_thats_using_this_manager_instance.uncle)
我正在寻找的魔法是“uncle=model_thats_using_this_manager_instance.uncle”。看来我应该能够以某种方式做到这一点。我知道我可以说 self.model
来获取模型,但如何获取实例?
class SupercalifragilisticexpialidociousManager(models.Manager):
# Sorry, I'm sick of Foo and Spam for now.
def get_query_set(self, account=None):
return super(SupercalifragilisticexpialidociousManager,
self).get_query_set().filter(uncle=model_thats_using_this_manager_instance.uncle)
The magic I'm looking for is the "uncle=model_thats_using_this_manager_instance.uncle". It seems like I should be able to do this somehow. I know I could say self.model
to get the model, but how to get the instance?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当您使用管理器时,要求实例是没有意义的。管理器是类级属性 - 如果您尝试执行
foo.objects.all()
,其中foo
是 Supercalifragilisticexpialidocious 的实例,您将明确收到错误:It doesn't make sense to ask for an instance when you're using a manager. Managers are class-level attributes - if you try and do
foo.objects.all()
wherefoo
is an instance of Supercalifragilisticexpialidocious, you will explicitly get an error:据我所知,您无法从管理器内部访问该模型。当管理者在整个桌子上操作时,这是没有意义的。
您应该在模型中
或在管理器中执行类似的操作:
As far as I know, you cannot access the model from inside a manager. It doesn't make sense as managers operate on the whole table.
You should do something like this in the model:
or in the manager:
在像
object.lated_name.create()
这样的方法中,Django 会发送一个hint
参数:我现在使用的是 Django 1.11。
In methods like
object.related_name.create()
under the hood the Djangos sends ahint
argument:I'm using Django 1.11 nowadays.
尝试
self.model
。来自文档
“另一件事需要注意的是 Manager 方法可以访问 self.model 以获取它们所附加的模型类。” — https://docs.djangoproject。 com/en/4.2/topics/db/managers/#adding-extra-manager-methods
得出答案的原因:当您从管理器调用 .create() 时,管理器知道要创建什么模型。
try
self.model
.From the Docs
"Another thing to note is that Manager methods can access self.model to get the model class to which they’re attached." — https://docs.djangoproject.com/en/4.2/topics/db/managers/#adding-extra-manager-methods
What led to the answer: The manager knows what model to create when you call .create() from the manager.