Monday, February 27, 2017

Re: Benefit of 'return Foo.objects.all()' in a ListView

Brilliant, thanks both, I've got it working in both ways!

Much appreciated,

Rich

On Saturday, February 25, 2017 at 2:14:10 PM UTC, Melvyn Sopacua wrote:

Hi Richard,

 

Don't be discouraged to ask questions. It's what the list is for.

 

Ludovic is right, you'd normally use the regroup tag. But let's say you wanted to do this, then get_queryset isn't the right method.

It should return a queryset, and one only.

 

On Saturday 25 February 2017 03:42:11 Richard Jackson wrote:

 

> class MyBlogPosts(generic.ListView):

> def get_queryset(self, request):

 

My bad: request is not an argument here.

 

> ...is it possible to return two uniquely identifiable sets - for

> example, if a model has a function which returns True or False, to

> return one set for all the True and one for all the False?

 

General overview:

 

The goal of a View is to turn a HTTP request into a HTTP response. A Template provides context to the template,

A ListView uses a Template to do that and is responsible for providing a list of ModelInstances to the template. The get_queryset() method is used to retrieve those instances.

 

So, the logical place to provide a different grouping of a queryset is in the part where it gets sent to the template:

 

class BlogRoll(generic.ListView):

def get_context_data(self, **kwargs):

# let ListView do the hard work first

context = super(BlogRoll, self).get_context_data(**kwargs)

# Now make two groups

qs = context['object_list']

group1 = [ obj for obj in qs if obj.boolean_method() is True ]

group2 = [ obj for obj in qs if obj.boolean_method() is False ]

# update the context

context.update(

{ 'group1': group1, 'group2': group2 }

)

# and return it

return context

 

 

--

Melvyn Sopacua

--
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+unsubscribe@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/31f0c37d-d38b-460c-a630-c39ef5c164f0%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment