Home > OS >  How to get model-objects using other models in django
How to get model-objects using other models in django

Time:11-29

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?

CodePudding user response:

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.

  • Related