How to query contents(posts/videos) of people, a user follows with Django ORM when the user's details and following list is in separate database

Viewed 81

Hey guys I recently starting working on a project where there are two different databases for storing user information and all the posted contents. I want to fetch and show, the contents posted by users who are in current user's following list.

If this was in a single database, I could use a join statement like this,

current_user = self.request.user.id
following_ids = self.request.user.following.values_list('id',flat=True)
posts = Content.objects.filter(Q(user_id__in=following_ids) | Q(user__id=current_user))

but since we use two different databases, how can I execute a similar query to show the contents.

Please do help.

Thanks

1 Answers

If you already have a router, you can just use that in your queryset to specify which db you want it to use so:

Content.objects.using('myotherdb').filter(
    Q(user_id__in=following_ids) | Q(user__id=current_user.id)
)
Related