我正在编写检查实例并找到其所有关系的例程(例如使用 instance._meta.get_all_related_objects())但是我找不到一种涉及OneToOneField的关系的方法。

例如,使用这两个模型:

class Main(models.Model):
    ...

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

给定一个“主要”实例,我应该找到其相关的OneToOne对象/类(显然没有KWWOWNNNES NAME)。

我怎样才能做到这一点?

有帮助吗?

解决方案

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])]
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top