[Fixed]-Understanding Django's ORM (Database Design with ForeignKey and QuerySets)

1👍

You don’t need a user_profile FK on Post model.
If you want to get access to all posts created by a User in order to display them on UserProfile, you can use this query, given a user_profile instance:

user_posts = user_profile.user.post_set.all()

user_profile has a user attribute because of the OneToOne field, which has a post_set attribute, which is already linked to your user and gives you all posts created by that user. Moreover, the post_set is a queryset as well, which means you can filter on it too:

user_profile.user.post_set.filter(title__icontains='Django')

The above code will give you all posts of the given user_profile that have ‘django’ in their title.

For further reference, consult django documentation on related objects and following relationships backward.

👤iulian

Leave a comment