Saturday, February 25, 2017

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

Apologies if this is too off-topic, but in the case of using a get_queryset() as below:

class MyBlogPosts(generic.ListView):
        def get_queryset(self, request):
                return self.model.objects.filter(user=self.request.user)

...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?

Right now I'm splitting them in the template in something such as the below:

<h2>True ones</h2>
{% for p in object_list %} <!-- This would ideally be a set called 'object_list_true' -->
    <ul>
        {% if p.true_or_false == True %}
            <li>{{ p.foo }}</li>
        {% endif %}
    </ul>
{% endfor %}

<h2>False ones</h2>
{% for p in object_list %} <!-- This would ideally be a set called 'object_list_false' -->
    <ul>
        {% if p.true_or_false == False %}
            <li>{{ p.foo }}</li>
        {% endif %}
    </ul>
{% endfor %}


Thanks, and apologies for the constant basic questions!

Rich



On Saturday, February 25, 2017 at 9:32:32 AM UTC, Melvyn Sopacua wrote:
Hi Richard,

On Friday 24 February 2017 15:51:15 Richard Jackson wrote:

> What is the advantage of including the get_queryset(self) function in
> a ListView? When I've run it with a very basic model ('Foo') there
> doesn't appear to be any difference with/without it - this could well
> be that my examples are currently too basic.

There is none. The benefit of the get_queryset() method is that you can
return something other than Foo.objects.all(). For example:

class MyBlogPosts(generic.ListView):
        def get_queryset(self, request):
                return self.model.objects.filter(user=self.request.user)
--
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/b8556d2f-079a-4ba0-9697-0dbaaa07823d%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment