SapphireSun
SapphireSun

Reputation: 9388

Django ORM: SELECT on field attributes

I have a model that contains a FileField. I want to search for a specific filename. How do I do it? I was trying:

MyModel.objects.get(document__name=FOO)

I got a Join on field 'document' is not permitted.

Thanks!

Upvotes: 0

Views: 360

Answers (3)

lprsd
lprsd

Reputation: 87087

Do this instead:

MyModel.objects.get(document__icontains='FOO')

Upvotes: 2

Alex Gaynor
Alex Gaynor

Reputation: 15009

You can filter on document, and it'll filter by the string that is the path on disk to the file.

Upvotes: 1

robhudson
robhudson

Reputation: 2658

The attributes of a FileField are not stored in the database, and cannot be used in a query. For example, the name is simply the upload_to string plus the filename. If you want to store extra data about the file you have to put that data into other fields on the database, as the example documentation shows with a Car having a name of "57 Chevy".

Also, typically the double underscore in Django's ORM denotes following a database relationship, either a ForeignKey or a ManyToMany. So in the example ORM call you provided, I would assume that MyModel had a field document that was either a ForeignKey or ManyToMany to another model, and that other model has a field called name. Which doesn't sound like is the case.

Hope that helps some.

Upvotes: 2

Related Questions