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!
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.
Do this instead:
MyModel.objects.get(document__icontains='FOO')
You can filter on document, and it'll filter by the string that is the path on disk to the file.
精彩评论