0
0
Djangoframework~30 mins

OneToOneField for one-to-one in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
OneToOneField for one-to-one
📖 Scenario: You are building a simple Django app to store user profiles. Each user has exactly one profile with extra information.
🎯 Goal: Create two Django models: User and Profile. Link them with a one-to-one relationship using OneToOneField.
📋 What You'll Learn
Create a User model with a username field
Create a Profile model with a bio field
Add a OneToOneField in Profile linking to User
Set on_delete=models.CASCADE for the OneToOneField
Use exact field and model names as specified
💡 Why This Matters
🌍 Real World
One-to-one relationships are common when you want to extend user information without changing the original user model.
💼 Career
Understanding OneToOneField is essential for Django developers building user profiles, settings, or linked data models.
Progress0 / 4 steps
1
Create the User model
Create a Django model called User with a single field username that is a CharField with max_length=30.
Django
Need a hint?

Use class User(models.Model): and define username = models.CharField(max_length=30).

2
Create the Profile model with bio field
Add a Django model called Profile with a bio field that is a TextField.
Django
Need a hint?

Define class Profile(models.Model): and add bio = models.TextField().

3
Add OneToOneField linking Profile to User
In the Profile model, add a OneToOneField called user that links to the User model with on_delete=models.CASCADE.
Django
Need a hint?

Use user = models.OneToOneField(User, on_delete=models.CASCADE) inside Profile.

4
Add __str__ methods for better display
Add a __str__ method to both User and Profile models. For User, return self.username. For Profile, return f"Profile of {self.user.username}".
Django
Need a hint?

Define def __str__(self): in both models returning the specified strings.