[Answer]-How Do I Select From Two Different Tables in Django?

1👍

You might not be able to do it with a single query. However, you can get the two querysets and use itertools to merge the two iterables.

Example, assuming you want the users’ posts and comments,

posts = user.posts_set.all() #or Posts.objects.filter(user=user)
comments = Comments.objects.filter(post_id__user=user)

import itertools
qs = itertools.chain.from_iterable([posts, comments])

Alternatively, if you are not slicing the queryset,

qs = posts | comments

Now, you can order by key:

qs_sorted = sorted(qs, key=lambda x: x.time_created)

You might want to limit the queryset to avoid unusual loading times, as the querysets are evaluated int he sorted function

0👍

To select a certain group of Posts:

filtered_posts = Posts.objects.filter(however_you_filter_your_queryset)

To get all of the Comments associated with a certain post:

related_comments = p.comments_set.all()

You could create a list of tuples where each holds (data_type, content, time):

tuple_list = []
for p in filtered_posts:
    post_tuple = ('post', p.content, p.time_created)
    tuple_list.append(post_tuple)
    related_comments = p.comments_set.all()
    for c in related_comments:
        comment_tuple = ('comment', p.content, p.time_created)
        tuple_list.append(comment_tuple)

You ultimately end up with a list of tuples containing all of the posts you grabbed along with the comments related to those posts. If you sort your list by the third element of the tuples, you’ll be sorting by the datetime field you’re after. You can also remove duplicates by making a set().

Leave a comment