Home > Back-end >  Fetching another models data from a queryset in django
Fetching another models data from a queryset in django

Time:12-21

I have following models

class Post(models.Model):
    title = models.CharField(max_length=150)
    content = RichTextField(blank=True, null=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

class SavedPost(models.Model)
    saved_post = models.ForeignKey(Post, on_delete=models.CASCADE)
    user = models.ForeignKey(User,related_name="saved_posts", on_delete=models.CASCADE)

I want to fetch the post details(title and content) of each saved post of individual users, I am able to get the queryset containing saved_posts of each user using following code

user = User.objects.get(id=1)
saved_post_qs = user.saved_posts.all()

the above provides all post.ids in a queryset, but what I want is title, content of post returned from saved_post_qs.

CodePudding user response:

user = User.objects.get(id=1)
saved_post_qs_pks = user.saved_posts.all().values_list('saved_post',flat=True).distinct()
posts = Post.objects.filter(pk__in==saved_post_qs_pks)
  • Related