11

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?

msampaio
  • 3,394
  • 6
  • 33
  • 53
  • Duplicate of http://stackoverflow.com/questions/687295/how-do-i-do-a-not-equal-in-django-queryset-filtering – Eren Güven Sep 13 '12 at 11:42
  • 1
    actually I think it is a simpler, clearer example for when to use exclude, the other question is a bit more complex on the face of it – Ctrlspc Sep 13 '12 at 12:06

1 Answers1

15

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')
Ctrlspc
  • 1,596
  • 1
  • 15
  • 22