views:

60

answers:

2

Hi,

I have a model with a decimal field. The output of:

def special_method(self):
    return MyClass.objects.filter(product=self).order_by('-date_active')[0:1]

on this model is:

[<MyClass: 10.00>]

... and I have defined the following method on MyClass:

def __str__(self):
    return str(self.rate)

This may be a silly question but how do I correctly return the decimal number instead of this strange object?

Thanks.

+1  A: 

myclass_instance.rate will give you the decimal number.

[edit]

Your method will then be something like:

def special_method(self):
    return MyClass.objects.filter(product=self).order_by('-date_active')[:1].values_list('rate', flat=True)

Or you might be able to do something like:

def special_method(self):
    return self.myclass_set.order_by('-date_active')[:1].values_list('rate', flat=True)
Will Hardy
Thanks, that worked when I added [0] on the end. Neat!
John
A: 

You're using filter, which always returns a QuerySet - a list-like collection of multiple instances - even if only one item is matched. You should use .get() instead, which will return a single item, and then you can access the .rate property on the returned instance.

Daniel Roseman
I don't think this is possible, because the characteristics of my specific model mean that multiple objects will usually be returned for the given input.
John