3

So I have three models

class Post(....

class Project(....

# have a many to many relationship
class ProjectPost(....
    post = ..... # foreignkey
    project = .... # foreignkey

The data set I want to select is a list of Post objects given a Project object.

This is what I tried:

posts_list = ProjectPost.objects.filter(project=project_object).select_related("post")

But this returns a list of ProjectPost objects rather than a list of Post objects. What is the correct way of doing this?

2 Answers 2

4

You may want to use the ManyToManyField()

https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/

You should do it like this:

class Post(models.Model):
    pass


class Project(models.Model):
    posts = models.ManyToManyField(Post)

And then, if you want to access the Posts of a Project, you can do

project_obj.posts.all()

You can use all the Queryset methods

If you want to access the projects of a posts you can do

post_obj.project_set.all()

Same as before, you can use all the Queryset methods.

If for any reason you want to do it that way, you could do:

post_list = ProjectPost.objects.filter(project=project_object).values('post')
Sign up to request clarification or add additional context in comments.

2 Comments

When I did "posts_list = project_object.objects.all()", I got the error: Manager isn't accessible via Project instances. Also I want to get the actual objects not just the ids, so ...values('post') by itself isn't what I'm looking for.
Done, you should do project_obj.posts.all(). Sorry, my bad (really, i'm sorry)
1

Came across this problem myself recently and this was how I solved it. Would love it if someone could comment on whether my solution is efficient.

project_posts = ProjectPost.objects.filter(project=project_object).select_related("post")
posts_lists = map(lambda post: project.post, project_posts)

Objects in posts_lists are now of the correct type.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.