python - Get related objects from a queryset, preserving the ordering -


i have model, looks this:

class agent(models.model):     class meta:         ordering = ['first_name', 'last_name', ]     first_name = models.charfield(max_length=100)     last_name = models.charfield(max_length=100)     ... other fields ...  class point(models.model):     agent = models.foreignkey(agent)     ... other fields ... 

when select points want them ordered agent names, this:

points = point.objects.filter(...smth...).order_by(-agent) 

so resulting queryset ordered agent names, z a

or

points = point.objects.filter(...smth...).order_by(agent) 

or without ordering

the question is: how queryset or list of unique agent objects points queryset, preserving ordering?

preferrably, without more order_by() statements, because view may or may not explicitly aware of ordering type

something set(points.values_list('agent', flat=true)), objects instead of pk-s?

you can use own idea , nest (where points queryset of point):

agent.objects.filter(id__in=points.values_list('agent', flat=true)) 

django orm translate single db query. should have agent's default order. in order preserve agent order in points, do:

[p.agent p in points.distinct('agent')] 

this workaround, obviously, not queryset , distinct field arguments supported in postgres.


Comments

Popular posts from this blog

java - Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener -

python - pip wont install .WHL files -

Excel VBA "Microsoft Windows Common Controls 6.0 (SP6)" Location Changes -