gpt4 book ai didi

python - Django - 如何将自定义对象分配为模型属性并在该对象中获取该模型实例?

转载 作者:行者123 更新时间:2023-11-30 21:52:22 25 4
gpt4 key购买 nike

我想将一些逻辑从模型中分离出来,并将其分组到一个属性中,就像 Django 对模型管理器(object 属性)所做的那样。事实上,类似于 ForeignKey 但没有数据库表示。

我有这样的东西:

class Remote(object):
def __init(self, *args, **kwargs)
self.post = ... # how to get to post instance?

def synchronize(self):
# this function requires Post object access
print(self.post.name)

class Post(models.Model):
name = models.CharField(max_length=100)
remote = Remote()

...

for post in Post.objects.all():
post.remote.synchronize()

问题

如何修改上面的代码来访问Remote对象中的Post对象?

其他问题

是否可以确定是否已从 Post 实例调用 Remote 对象(post.remote... – 如上所示)或Post 类(Post.remote...)?

最佳答案

您想要的可以通过 descriptors 来实现.

为了使其工作,您需要在您的类中定义一个 __get__ 方法,您希望该方法可以作为另一个类的属性进行访问。

您的案例的简单示例如下所示:

class Remote:
def __init__(self, post)
self.post = post

def synchronize(self):
print(self.post.name)


class RemoteDescriptor:
def __get__(self, obj):
if not obj:
return self
remote = getattr(obj, '_remote', None)
if not remote:
remote = Remote(obj)
obj._remote = remote
return remote


class Post(models.Model):
name = models.CharField(max_length=100)
remote = RemoteDescriptor()

说明:

在上面的代码中,每次调用 Post 模型的远程属性时,都会调用 RemoteDescriptor__get__ 方法。首先检查 obj 是确保从其他对象调用描述符,而不是直接调用。这里需要两个类 Remote 和 RemoteDescriptor,以便您能够在描述符中添加可使用点访问的自定义方法(例如 post.remote.calculate())

另请注意,我在第一次调用时将 Remote 实例放置到 Post 的字典中,并且在所有后续调用中,对象将从那里返回。

您还应该检查 great article关于 RealPython 上的描述符。

关于python - Django - 如何将自定义对象分配为模型属性并在该对象中获取该模型实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59902479/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com