Django

Many to One Relationships | Using Foreign Key

brian | Published: Feb. 14, 2024, 3:19 p.m. | Updated: May 25, 2025, 5:14 p.m.

Profile Picture

What is a Many to One Relationship?

 


class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.CharField(max_length=200, null=True, blank=True)
  

class Tweet(models.Model):
    profile = models.ForeignKey(Profile, related_name='tweets', on_delete=models.CASCADE)
    content = models.TextField(max_length=280, null=True, blank=False)
  
  
 

The best way to show how a Many to One relationship works or what it is more specifically is with a real life example. Above what we have created is an example of how a twitter app can be made, at the simplest level. So we have a Profile model, and a Tweet model. Here we set a relationship between the Profile model and the tweet model using a foreign key. This basically states One user/profile can have multiple tweets, but a tweet object can only have one author, now this makes sense. For example when you create a tweet or a instagram post, or even a facebook post, the author of that post is only YOU....  its not me and you, and someone else, its ONLY YOU, and at the same time YOU can create as many tweets and posts as you want later on that day.

 

As for the fields I included in the foreign key, the first one is the related table, which in this case is the profile. The related name  allows us to specify the reverse relation name from the Tweet model back to the Profile model. For example;

@login_required
def profile(request, pk):
    
    user1 = get_object_or_404(User, pk=pk)
    profile = user1.profile
    tweets = profile.tweets.all().order_by('-created_at')
    

    
    context = {
        'tweets':tweets,
        'user1':user1,
        'profile':profile,
        'tweet_count':tweet_count

    }
    return render(request, 'twitter_user/profile.html', context)

here I obtained the profile, and then I retrieved all the tweets from that certain profile by calling the "tweets" which is the same name I gave in the arguments above.

The last argument which is the on_delete, specifies what happens to the tweet if the profile gets deleted, for example: Lets say you want to delete your twitter account, well if you do delete it, you don't want the tweet to still be there on the internet, you want to delete it aswell, so the on_delete=models.CASCADE states that if you delete the profile, then also delete the tweet.

 

Below is an example of one of my projects I made, its a twitter clone type project, but it demonstrates the usage of Many to One relationship

Here I am viewing my profile, and it's showing all the tweets I've made. At the same time the tweets themselves only have one author, which is me.