Returning unique values from a foreign key in a ListView

40 views
Skip to first unread message

Richard Jackson

unread,
Mar 31, 2017, 5:29:17 PM3/31/17
to Django users
Hi everyone,

Goal
- I have a ListView built around ModelA. 
- ModelA has a foreign key to ModelB. 
- I want to return a list with all unique entries of a required field (i.e. 'foo') from ModelB.

Context
I have a table of clients (ModelA) and a table of jobs I do (ModelB), connected via foreign key - I want to retrieve a distinct list of all the jobs I do for the clients so I can render that into the template and make a user-facing filter.

Problem 1
Can't access values in ModelB using get_queryset()  as using this for ModelA and I don't know how to query multiple tables in such a statement:

views.py


from .models import ModelA
from django.views.generic import ListView, DetailView


# Create your views here.
class IndexView(ListView):
    context_object_name
= 'modela_list'
    template_name
= 'modela/index.html'


   
def get_queryset(self):
       
return ModelA.objects.order_by('title')


Outcome 1
Couldn't work out how to return the data from ModelA *AND* a unique list of 'foo' values. Can return ALL values of 'foo' including duplicates (i.e. 'Hello', 'Hello', 'World', 'World', 'Hello', rather than the desired 'Hello', 'World')

Problem 2
Tried to do get_context_data though my understanding of this is very weak:

views.py



[code from Problem 1]
   
[...]
   
def get_context_data(self, **kwargs):
        context
= super(IndexView, self).get_context_data(**kwargs)
        qs
= context['modela_list']
        list_of_values
= qs.order_by().values('foo').distinct()
        context
.update(
           
{
               
'list_of_values': list_of_values,
           
}
       
)
       
return context


Outcome 2
Could return the unique values for the FOREIGN KEY values as they are in ModelA, could not return the assigned values from ModelB (i.e. '1', '2' returned, instead of 'Hello', 'World')

Overall Outcome
So I've managed to either get ALL the values of the required field from ModelB OR I can get the distinct values of the foreign key field from ModelA - but not the distinct values of the required field from ModelB!

Any help would be greatly appreciated!

Rich
Reply all
Reply to author
Forward
0 new messages