GauravGenric
GauravGenric

Reputation: 1

How to convert SearchQuerySet into QuerySet without changing order?

I have doctors object of SearchQuerySet type and i want to convert into QuerySet:

doctors = SearchQuerySet().dwithin('location', point_data, max_dist).distance('location',point_data).order_by('distance')

results = [ r.pk for r in doctors ]

address_key = Address.objects.all()

add_obj = address_key.filter(pk__in=results)

Now add_obj is type of QuerySet.

add_obj queryset does not have same order like doctors SearchQuerySet has order of pk.

Upvotes: 0

Views: 414

Answers (1)

Alasdair
Alasdair

Reputation: 309089

It isn't possible to use the order of the list when using pk__in.

An alternative is to use in_bulk to fetch all of the objects, keyed by id. Then construct an ordered list using a list comprehension.

results = [r.pk for r in search_results]
objects = MyModel.objects.in_bulk(results)
objects_in_order = [obj[pk] for pk in objects]

Upvotes: 1

Related Questions