art.zhitnik
art.zhitnik

Reputation: 624

Using __unicode__ of a model as a search field in admin form

Is there a way of including model's __unicode__ method to search_fields tuple? I don't want to create special field for storing result of the __unicode__ in the model, because this value depends of the several other models...

Upvotes: 2

Views: 1028

Answers (2)

San4ez
San4ez

Reputation: 8241

No, it is not possible, because fields mentioned in search_fields tuple are used to construct sql query

Look https://github.com/django/django/blob/master/django/contrib/admin/views/main.py lines 349-370

UPD. Well, you can create another field and store value of __unicode__ method there. Probably it looks ugly and inefficient but this allows you to filter database column. Give me more information how __unicode__ method looks.

UPD2 Your unicode method:

def __unicode__(self):
    return "%s%s%s%s-%s%s" % (
        self.factory.republic.code.upper(),
        self.factory.location.region and self.factory.location.region.code or '00', 
        self.factory.location.code, 
        self.factory.code, 
        self.kind.code, 
        self.code
    ) 

Django search_fields operates his ORM methods so if you cannot perform Catalog.objects.filter(**lookup_queries), you will not be able to do that with search_fields in admin. Unfortunately.

You unicode method is really specific with join of 6 tables and other program logic. Searching this field will be complicated in SQL language, and will not use index. Try to save result in db column and update when related fields update too.

Upvotes: 2

Joseph Victor Zammit
Joseph Victor Zammit

Reputation: 15320

Hey I did require something similar recently. As explained in this answer search_fields only works with attributes that represent columns in the database, not with properties.

However if your __unicode__ function depends of the [fields within] several other models look at this other answer which explains how to specify related field searches in the admin search_fields the same way you do on Django querysets.

Upvotes: 1

Related Questions