Let's say I have two models, for example:
class Product:
product_name = models.CharField(max_length=40)
class ProductPrice(models.Model):
product = models.OneToOneField(Product, on_delete=models.CASCADE)
product_price = models.FloatField()
Please don't bother why someone might want two different models/tables for such data. That's not the main point here. What's interesting is, when I query a Product I will get a python attr productprice along with the object ONLY IF ProductPrice exist associated with that Product.
To make this more clear let's create some dummy data:
product1 = Product.objects.create(product_name='first product')
product2 = Product.objects.create(product_name='second product')
product_price = ProductPrice.objects.create(product=product2, price=10.99)
Now try this
print(hasattr(product1`, "productprice")) # -> false
print(hasattr(product2`, "productprice")) # -> true
How does django know that a ProductPrice exist in database? In SQL I am not aware of any way to check this without second query. I am very curious how this works.