Django Admin, FileField and __unicode__()
The FileField or ImageField is used in many situations (for storing avatars, albums etc). Using it's details in the admin can result in high loading times if you add them in the model's __unicode__().
Simple Example
Let's say you use for storing the avatar of your users (UserProfile has a FK to Avatar):
- class Avatar(IKImage):
- the_image = models.ImageField(upload_to='/your/path')
In the admin you need to be able to differentiate between Avatars so you need a __unicode__() method.
Ideally you need to show something related to the file and what else if not the url:
- def __unicode__(self, *args, **kwargs):
- return u'%s' % self.original_image.url
For a few records, you will not notice any problem, but as your project grows, the loading time of admin Profile edit page will increase.
Why does loading time increase?
When getting the url of the file, django will acces the storage, which response time will always be slow. So make sure you use something that exists in the database.
The fast way
Use database fields to keep things smooth. The field containing the filename in the database is name. You are not used to it but this is a good place to take advantage of it.
- def __unicode__(self, *args, **kwargs):
- return u'%s' % self.original_image.name



Leave a Comment :