Consider these Django models:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField()If you have a User instance u, what does u.profile return?
Think about how OneToOneField creates a direct link between two models.
OneToOneField creates a single related object accessible as an attribute. Accessing u.profile returns the linked Profile instance or raises DoesNotExist if none exists.
Choose the correct syntax to define a one-to-one relationship from Profile to User:
OneToOneField is a specific field type in Django models.
Only models.OneToOneField correctly defines a one-to-one relationship. ForeignKey with unique=True is not recommended for this purpose. ManyToManyField and OneToManyField do not exist or do not represent one-to-one.
Given these models:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
u = User.objects.create(username='alice')
print(u.profile)This code raises Profile.DoesNotExist. Why?
Think about what happens if the related object is missing.
Accessing u.profile tries to find a Profile linked to u. If none exists, Django raises Profile.DoesNotExist. The other options are incorrect because null=True is not required, the reverse attribute is created automatically, and on_delete does not delete the user here.
Given these models and code:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.CharField(max_length=100)
u = User.objects.create(username='bob')
p = Profile.objects.create(user=u, bio='Hello')
print(u.profile.bio)What will be printed?
Remember that u.profile accesses the related Profile instance.
The code creates a User and a linked Profile with bio 'Hello'. Accessing u.profile.bio prints 'Hello'.
In Django, both OneToOneField and ForeignKey with unique=True can enforce one-to-one relationships. Why is OneToOneField preferred?
Think about how Django creates reverse relations and the developer experience.
OneToOneField automatically creates a reverse attribute on the related model, making it easier to access the linked object. ForeignKey with unique=True can enforce uniqueness but does not create a clear reverse one-to-one relation. Option A is incorrect because unique=True does enforce uniqueness. Option A is false because OneToOneField allows only one related object. Option A is false because ForeignKey with unique=True is still supported.