10

I have a similar model

Class Student(models.Model):
"""A simple class which holds the basic info
of a student."""

name = models.CharField(max_length=50)
age = models.PositiveIntegerField()
photo = models.ImageField(upload_to='foobar', blank=True, null=True)

As we can see photo field is optional. I wanted all the students who have their images saved in the college DB. For that i did this

>>> Student.objects.exclude(photo__name=None)

But i am getting this error :

FieldError: Join on field 'photo' not permitted.

So, How can i extract all those students having their photos?

Any sort of help regarding this would be appreciated. Thanks in advance.

Baishampayan Ghose
  • 19,928
  • 10
  • 56
  • 60
aatifh
  • 2,317
  • 4
  • 27
  • 30

1 Answers1

13

It doesn't work because field lookups only work on other models. Here, name is an attribute on the return value of your photo field.

Try this instead:

Student.objects.exclude(photo__isnull=True)

It is preferred to use isnull instead of comparing equality to None.

EDIT:

Jeff Ober's suggestion:

Student.objects.exclude(photo='')

He says filtering is performed on the actual values stored in DB. In a file field's case the path to the file.

Community
  • 1
  • 1
muhuk
  • 15,777
  • 9
  • 59
  • 98
  • It doesn't work. It actually returns all the students objects. May be because photo field is actually a photo object like this So, it will always return True. – aatifh May 12 '09 at 10:29
  • 4
    The query is executed against the value stored in the database, which is the location of the photo. You might try something like Student.objects.exclude(photo=''). isnull only works when the value is actually stored as null. If the entry is created via admin, it will get a blank value (empty string) rather than null. – Jeff Ober May 12 '09 at 12:28
  • @Jeff: I've added your suggestion. But I have my doubts that empty values will be None/NULL instead of zero length strings. It's not a good idea to set null=True on string columns. Causes ambiguation between None & ''. – muhuk May 12 '09 at 13:22