Search code examples
djangometadataone-to-one

Get the Model of a OneToOne


I need to get the Model of a OneToOne related model:

class ModelA(models.Model):
    name = models.CharField(...)

class ModelB(models.Model):
    target = models.OneToOneField(
        ModelA, 
        related_name="model_a", 
    ...) 

When I use an instance of ModelB to get the class of its target field with:

 modelb_instance.model_a._meta.model 

I get an error:

ForwardOneToOneDescriptor' object has no attribute '_meta' 

I am aware that this cannot be done on OneToOne attribute, but I am not sure how to retrieve ModelA model name. Any help would be appreciated

As @Willem suggested working though the Options of a ModelB did the job: modelb_instance._meta.get_field('target').related_model


Solution

  • You can work with:

    ModelB.target.field.related_model

    or for a modelb_instance:

    type(modelb_instance).target.field.related_model

    or we can work through the Options of ModelB with:

    modelb_instance._meta.get_field('target').related_model