Using a Haystack Result within Django ORM

325 views Asked by At

I am filtering userprofiles via their interests using Haystack. How can I use Haystack's result to query a model to return me all selected users belonging to these userprofiles?

Right now I am doing it the following way, but it is really slow, as haystack_results can be a list of many thousands of entries:

haystack_results = SearchQuerySet().raw_search('coffee AND django_ct:common.profile').values_list('pk', flat=True)
User.objects.filter(profile__id__in=haystack_results)

User and Profile have a OneToOne Relationship:

class Profile(models.Model):
    user = models.OneToOneField(...)

Do you know any better way?

Thanks for your help, Matthias

1

There are 1 answers

0
kaay On BEST ANSWER

You could do one of the following:

  1. Add a separate SearchIndex indexing the User model using the data from Profile (and query using .models(User))
  2. Add a stored data field to your ProfileIndex (I'm assuming that's what you named it), storing the profile's .user_id. Use that in your values_list, and profile__id__in becomes id__in.
  3. Wait for load_all to support prefetching related data (unlikely to happen soon)
  4. Have your Profile inherit from User. Note: I do not know for sure if Django does a join each time, or a lazy load once a parent field is requested.