Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

382
Views
How to get model-objects using other models in django

I need if user requests to get the following page the response of the request would be the page containing specific posts made by the users who is followed by the user who requests. I thought to do some actions to do this:

  1. Get the requester
  2. Get the users who are followed by the requester
  3. Get the posts created by the users the who are being followed

In my models.py:

class User(AbstractUser):
    image_url = models.CharField(max_length=5000, null=True)


class Follow(models.Model):
    follower = models.ForeignKey(
        User, on_delete=models.PROTECT, related_name="follower")
    following = models.ForeignKey(
        User, on_delete=models.PROTECT, related_name='following')


class Post(models.Model):
    content = models.CharField(max_length=140)
    date_created = models.DateTimeField(auto_now_add=True)
    poster = models.ForeignKey(User, on_delete=models.CASCADE)

In my views.py:

def following_page(request, username):
    user = User.objects.get(username=username)
    f = user.following.all()
    posts = Post.objects.filter(poster=f.following)
    posts = posts.order_by("-date_created").all()
    return render(request, 'network/index.html', {
        "posts": posts
    })

It says

AttributeError 'QuerySet' object has no attribute 'following'

Should I have to change the model? How to solve the problem?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You can filter with:

from django.contrib.auth.decorators import login_required

@login_required
def following_page(request):
    posts = Post.objects.filter(poster__following__follower=request.user)
    return render(request, 'network/index.html', {
        'posts': posts
    })

Since you use the logged in user, one uses request.user, and thus it makes no sense for the view to accept a username.


Note: You can limit views to a view to authenticated users with the @login_required decorator [Django-doc].


Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!