Home > Back-end >  How to make Django queries with associated tables?
How to make Django queries with associated tables?

Time:09-17

I'm trying to create a 'saved post' feature on a website. I'm struggling with how to create a query that I can use to populate my HTML template with posts.

Here are my models:

class User(AbstractUser):
     pass

class Post(models.Model):
    title = models.CharField(max_length=200)
    description = models.CharField(max_length=500)

class SavedPost(models.Model):
     post = models.ForeignKey(Post, on_delete=models.CASCADE)
     user = models.ForeignKey (User, on_delete=models.CASCADE, null=True)

My .views looks like this

def savedpostsview(request):
    posts = Post.objects.all
    savedposts = posts.savedpost_set(user = request.user)
    return render(request, "posts/savedposts.html",{
        'savedposts': savedposts
    })

Right now I'm getting the error "'function' object has no attribute 'savedpost_set'".

I know I'm getting something wrong syntactically, but I've been reading documentation forever and can't figure out what it is for the life of me. Does anybody have any insight into what I'm doing wrong?

CodePudding user response:

first of all here Post.objects.all all() is a function and thats why error is "'function' object has no attribute 'savedpost_set'"

You should call Post.objects.all() this will return queryset.

Then You are trying to reverse query on queryset which not possible and will throw error.

All you want is this Post.objects.filter(savedpost__user=request.user)

  • Related