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