Django:查找指向模型的所有 OneToOneFields

发布于 2024-10-22 03:59:15 字数 357 浏览 10 评论 0原文

我正在编写例程来检查实例并查找其所有关系(例如使用instance._meta.get_all_lated_objects()),但我找不到获取涉及 OneToOneField 的关系的方法。

例如,对于这两个模型:

class Main(models.Model):
    ...

class Extension(models.Model):
    ...
    main = models.OneToOneField(Main, primary_key=True)

给定一个“Main”实例,我应该找到其相关的 OneToOne 对象/类(显然不知道它们的名称)。

我怎样才能做到这一点?

I'm writing routines to inspect an instance and find all its relations (e.g. using instance._meta.get_all_related_objects()) but I can't find a way to get relations involving a OneToOneField.

For instance, with these two models:

class Main(models.Model):
    ...

class Extension(models.Model):
    ...
    main = models.OneToOneField(Main, primary_key=True)

given a 'Main' instance I should find its related OneToOne objects/classes (obviously without kwowing their names).

How can I do that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦纸 2024-10-29 03:59:15
from django.db import models

def all_models_with_oto(the_model):
    """
    Returns all models that have a one-to-one pointing to `model`.
    """
    model_list = []
    for model in models.get_models():
        for field in model._meta.fields:
            if isinstance(field, models.OneToOneField):
                if field.rel.to == the_model:
                    model_list.append(model)
    return model_list

列表理解版本(讽刺的是更慢,可能是由于 any 和嵌套列表):

def all_models_with_oto(the_model):
    """
    Returns all models that have a one-to-one pointing to `model`.
    """
    return [model for model in models.get_models() if any([isinstance(field, models.OneToOneField) and field.rel.to == the_model for field in model._meta.fields])]
from django.db import models

def all_models_with_oto(the_model):
    """
    Returns all models that have a one-to-one pointing to `model`.
    """
    model_list = []
    for model in models.get_models():
        for field in model._meta.fields:
            if isinstance(field, models.OneToOneField):
                if field.rel.to == the_model:
                    model_list.append(model)
    return model_list

List comprehension version (ironically slower, probably due to any and nested lists):

def all_models_with_oto(the_model):
    """
    Returns all models that have a one-to-one pointing to `model`.
    """
    return [model for model in models.get_models() if any([isinstance(field, models.OneToOneField) and field.rel.to == the_model for field in model._meta.fields])]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文