[Django]-Django return foreign key object from queryset?

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')
๐Ÿ‘คiferminm

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.

๐Ÿ‘คblinduck

Leave a comment