How to get all the OneToOne relations if exists, of a model instance?

With the same example in Django documentation for One-to-one relationships,

from django.db import models


class Place(models.Model):
    name = models.CharField(max_length=50)
    address = models.CharField(max_length=80)

    def __str__(self):
        return f"{self.name} the place"


class Restaurant(models.Model):
    place = models.OneToOneField(
        Place,
        on_delete=models.CASCADE,
        primary_key=True,
    )
    ...

    def __str__(self):
        return "%s the restaurant" % self.place.name

we can use hasattr(p2, "restaurant") to know if a Place have an associated Restaurant object or not.

If the Place have multiple OneToOne associations, how to know if all the associations exist or not or the associations that exist?

I have this working code, but it is making database query for each association. How to fetch all the existing relations in a single database query?

def all_relations_exist(request: HttpRequest, *args, **kwargs):
    for f in p2._meta.related_objects:
        if f.one_to_one:
            accessor_name = f.get_accessor_name()
            if not hasattr(p2, accessor_name):
                return False
    return True

Thanks

Do you know all the models that may have a relationship with Place?

If so, I think you can do a query with a select_related to those models, then check for their existence individually. (If not, you could probably dynamically construct the entries for that function.)

Well, this works in views. But how do I make it a Model Method, that I can call select_related on self itself?

It wouldn’t be in the model method, it would either be a custom queryset or a method in the manager. (You would want the select_related as part of the query that is retrieving that instance of the model, not as a method on the instance - at that point it’s too late.)

It is custom queryset that is fetching all the required related objects and a Model method.

Thanks