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

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/10f50536-b5cc-4e30-8d28-a8ca1e0dce29%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to