Here is my issue I have a Model like this
class Item(models.Model):
name = models.Charfield(maxlength=100)
user = models.ForeignKey(User)
def get_user_name(self):
return self.user.name
class Admin:
list_display = ('name', 'get_user_name')
ordering = ('get_user_name', 'name')
As you can see, I'm trying to display the foreign value name, and
then order by it as well. I get a big traceback which amounts to
something along the lines of "can't query for this". I'm assuming
that the ordering tuple instructs django.admin to use ordering in
it's SQL query, which it obviously can't do here because
get_user_name is a python method.
This seem like a relatively simple use case and I'm sure there is
probably a simple way to do it that I just haven't found.
Thanks,
-Mikeal
Hi Mikael,
You can't order by the result of a Python function, because the
ordering clause happens at the SQL level, not in Python.
--
Adrian Holovaty
holovaty.com | djangoproject.com
How about ordering by a ForeignKeyField?
snippet follows:
class Model(models.Model):
opis = models.CharField(maxlength=50)
znamka = models.ForeignKey(Znamka)
def __str__(self):
return "%s %s" % (self.znamka, self.opis)
class Admin:
list_filter = ['znamka'] # sidebar with handy filters
class Meta:
verbose_name_plural = "Modeli"
ordering = ['znamka', 'opis']
In the memorable words of Dr. Jones... "this doesn't seem to work" =)
Regards,
--
Carlos Yoder
http://carlitosyoder.blogspot.com
The problem was because I was trying to sort by a field that was not
listed on Admin.list_display
Updated code:
class Model(models.Model):
opis = models.CharField(maxlength=50)
znamka = models.ForeignKey(Znamka)
def __str__(self):
return "%s %s" % (self.znamka, self.opis)
class Admin:
list_filter = ['znamka'] # sidebar with handy filters
list_display = ('znamka', 'opis')
class Meta:
verbose_name_plural = "Modeli"
ordering = ['znamka','opis']
Like a charm, it works.
=)