开发者

Django: find all OneToOneFields pointing to a Model

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 OneToOneFie开发者_如何转开发ld.

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?


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜