I have a multi model with different OneToOne relationships from various models to a single parent. Consider this example:
class Place(models.Model):
name = models.CharField(max_length=100)
address = models.CharField(max_length=100)
...
class Restaurant(models.Model):
place = models.OneToOneField(Place)
...
class Shop(models.Model):
place = models.OneToOneField(Place)
...
Regardless if the above model makes sense in real life scenario, how can someone identify if an object of Place has a relationship to any of the other models, in django view?
In a template, you can say
The reason for this is that
OneToOneFieldentries actually create an attribute in the model they are referencing. In normal Python code, sayingplace.restaurantwhere no restaurant is defined will throw an exception, but templates will swallow such exceptions.If you do need to do something like this in Python code, the simplest-to-understand way is to wrap it in a try/except block:
EDIT: As I say in my comment, if you only want a
Placeto be either aRestaurantor aShopbut never both, then you shouldn’t be usingOneToOneFieldand should instead use model inheritance.Assuming that a
Placecould have two or more other possibilities, I recommend doing something like this:The above would let you say
place.relationshipsand get back a dictionary that looked likealthough one or both of those might be missing, depending on whether they exist. This would be easier to work with than having to catch a potential exception every time you reverse the
OneToOneFieldrelationship.