django show feature blogs first

Hi,

in this basic blog, i need to show feature blogs first ( if there any ), and then show the rest of blogs, based on ‘post.id’.

class Post(models.Model):
    vip  = models.PositiveSmallIntegerField()   # feature blog
    ...

index.html

{% for post in post_list %}            
    <li><h5> ID= {{ post.id }}
                {% if post.vip %} | 
                    vip= {{post.vip}} 
                {% endif %} </h5></li>                              
{% endfor %}

views.py

class PostList(generic.ListView):
    queryset = Post.objects.all().order_by('-vip', 'id') 
    template_name = 'index.html'

the result 1:

  • ID= 4 | vip= 2 # vip shows first :slight_smile: but in descending order :frowning:

  • ID= 3 | vip= 1

  • ID= 1 # now shows the rest of blogs based on id :slight_smile:

  • ID= 2

views.py

class PostList(generic.ListView):
    queryset = Post.objects.all().order_by('vip', 'id') 
    template_name = 'index.html'

the result 2:

  • ID= 1

  • ID= 2

  • ID= 3 | vip= 1

  • ID= 4 | vip= 2

what i need is:

  • ID= 4 | vip= 1 # first shows blogs by vip in ascending order ( if there are any post.vip )

  • ID= 3 | vip= 2

  • ID= 1 # then show blogs by id…

  • ID= 2

Thanks in advance
Ali

See the docs at Using F to sort null values.

it’s works,

many thanks @KenWhitesell :slight_smile:

from django.db.models import F



class PostList(generic.ListView):
    queryset = Post.objects.all().order_by(F('vip').asc(nulls_last=True),'id') 
    template_name = 'index.html'