Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting all objects of model except

Let the models class:

class MyModel(models.Model):
    name = models.CharField(max_length=200)
    category = models.CharField(max_length=200)

I want to get all the objects of MyModel except those with a specific category. I'm using this code:

[mm for mm in MyModel.objects.all() if mm.category != u'mycategory']

Is there another solution for this question?

like image 455
msampaio Avatar asked Sep 13 '12 11:09

msampaio


1 Answers

Take a look at this documentation: https://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-specific-objects-with-filters , you want to use an exclude filter.

So somethig like:

objects = MyModel.objects.exclude(category= u'mycategory')
like image 76
Ctrlspc Avatar answered Oct 17 '22 13:10

Ctrlspc