3👍
✅
The uploaded_by
field refers to a MyProfile
model, not a User
model. You can change the query to:
user_posts = MyPost.objects.filter(
uploaded_by__user=self.request.user
).order_by('-cr_date')
So by using double underscores (__
) we look “through” a relation, and we thus look for MyPost
objects where the uploaded_by
is a MyProfile
with as user
a reference to the request.user
object.
If you want to display content of the user with the pk
in the path:
path('myprofile/<int:pk>', views.MyProfileDetailView.as_view()),
you can replace this with:
user_posts = MyPost.objects.filter(
uploaded_by_id=self.kwargs['pk']
).order_by('-cr_date')
given the pk
is the profile id; or:
user_posts = MyPost.objects.filter(
uploaded_by__user_id=self.kwargs['pk']
).order_by('-cr_date')
if the pk
refers to the user id.
Or you can make use of self.object
:
user_posts = self.object.mypost_set.order_by('-cr_date')
Source:stackexchange.com