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

时间:2011-03-16 15:43:12

标签: django-orm inspect one-to-one

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

例如,使用这两个模型:

class Main(models.Model):
    ...

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

给定一个'Main'实例,我应该找到它相关的OneToOne对象/类(显然没有知道它们的名字)。

我该怎么做?

1 个答案:

答案 0 :(得分:2)

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])]