[Fixed]-Fetching objects and combining them in one list

1👍

Firstly, you don’t need to build up the separate list in the first place, nor do you have to query Freelancers specifically. For any User instance, user.freelancer will give you the related Freelancer object via the one-to-one relationship.

The only problem with that is that the first time you do that access for any User you will incur another database call (subsequent access from the same User instance will be cached, though). You can avoid this by doing select_related on the initial query:

users = User.objects.filter(type=1).select_related('freelancer')

0👍

You could get all the freelancers using something like:

freelancers = Freelancer.objects.filter(user__type=1)

Since freelancer has a one-to-one with user, freelancer.user will give you the associated user.

As an optimization, if you know you are going to access all the users, you could do:

Freelancer.objects.filter(user__type=1).select_related('user')

This fetches both Freelancers and Users from the db.

Leave a comment