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