user2545177
user2545177

Reputation: 81

How to sort a django query with a specific value?

I have a model like this in Django:

 class Session(models.Model):
        user = models.ForeignKey(User)
        session_name = models.CharField(max_length=254)
        server_full_path = models.CharField(max_length=254)      # Contains server
        server_name = models.CharField(max_length=254)           #Server Name or IP
        file_path = models.CharField(max_length=254)             #full file path
        source_username = models.CharField(max_length=100)
        source_password = models.CharField(max_length=100)
        make_default = models.BooleanField()

I am using this query to get all the server_id:

all_server_id = Session.objects.filter(user_id=request.user.id)

I want to the query to be sorted in a such a way that the value with make_default=1 will come at first. I want this to show in the template. How can I do this?

Upvotes: 0

Views: 76

Answers (2)

Nafiul Islam
Nafiul Islam

Reputation: 82470

All you have to do is this:

all_server_id = Session.objects.filter(user_id=request.user.id).order_by('-make_default')

I believe that answers your question from the comments.

Upvotes: 0

arturex
arturex

Reputation: 568

If you want to sort a query, you should use order_by() function, ex:

all_server_id = Session.objects.filter(user_id=request.user.id).order_by('make_default')

Upvotes: 1

Related Questions