views:

437

answers:

1

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.

+4  A: 

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.

muhuk
It doesn't work. It actually returns all the students objects. May be because photo field is actually a photo object like this <ImageFieldFile: None> So, it will always return True.
aatifh
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
muhuk
@Jeff Ober Thanks, it works :)
aatifh