I followed some questions on this site to add a new column in the Django admin based on a model method. It works great. However, I cannot sort on the column. Is there a way to accomplish a sort on a model method field where there is no physical model field to reference?
For example one method looks up a foreign key relationship to another model and it returns strings. They could be alphabetically sorted. Another example checks to see if the model is active based on whether there is a termination date or not. (Obviously I can easily add a boolean
field to the model, but I want to know if this can be accomplished by just using methods instead). Is there a way to enable sorting on these "columns"?
Update: this is a non-rel backend (mongo), so foreign key lookups won't natively work.
Ex.
class mymodel(models.Model):
user = models.ForeignKey(User)
termination_date = models.DateTimeField(blank=True, null=True)
# Useful admin view methods
# Returns whether the model is currently active.
def is_active(self):
if self.termination_date:
return False
else:
return True
is_active.boolean = True
is_active.admin_order_field = 'termination_date' #<--- This activates sort, but not on the boolean, it sorts on the Model Field termination_date.
# Returns the username from foreign key relationship
def get_username(self):
return User.objects.get(pk=self.user_id).username
get_username.short_description = 'user'