Django admin search_fields with model property
I'm trying to use a 开发者_Go百科property in my model as a field in django admin (1.2).
Here's an example of my code:
class Case(models.Model):
reference = models.CharField(_(u'Reference'), max_length=70)
client_read = models.BooleanField(default=0)
def __unicode__(self):
return self.case_id
@property
def case_id(self):
""" unique case ID """
number = (settings.CASE_ID_LENGTH - len(str(self.id))) * "0" + str(self.id)
return '%(year)s%(unique_id)s' % {
'year': self.case_date.strftime("%y"),
'month': self.case_date.strftime("%m"),
'unique_id': number}
and the part of admin.py:
class OrderAdmin(ReadOnlyAdminFields, admin.ModelAdmin):
[...]
search_fields = ('id','case','req_surname','req_forename','req_company')
I can refer to the field as 'case' (like given in the example), but this gives me a TypeError: Related Field has invalid lookup: icontains
Of course it's working the way with related fields: so I can use case__id and then I'm able to use the id as search query. But this is somewhat irritating to the users cause the caseid is shown different.
Is there a way to use the case_id as search query like it's shown (year+month+id)?
No you cannot use it that way, because this only works with attributes that represent columns in the database, not with properties. The only way to make this work would be using a subclass of contrib.admin.views.main.ChangeList
for the change list and overwrite it's get_query_set
method to achieve the desired behaviour!
精彩评论