Reputation: 257
I have a model like this:
class Integer(models.Model):
integer_value = models.IntegerField(default=0)
current_price = models.DecimalField(max_digits=5, decimal_places=2, default=0.00)
share = models.IntegerField(default=0)
market = models.ForeignKey(
IntegerMarket,
on_delete=models.CASCADE,
related_name='integers',
default=None)
def __str__(self):
return str(self.integer_value)
class Meta:
ordering = ['integer_value']
I'm using the following view:
class IntegerMarketDetailView(LoginRequiredMixin, DetailView):
model = IntegerMarket
template_name = 'integer_market_detail.html'
login_url = 'login'
In my template, which is for a given instance of IntegerMarket
, I would like to extract the minimum and maximum values of integer_value
, in order to then define the min and max value of an axis in JavaScript.
For example, I might have an instance of IntegerMarket
featuring five integers
, with integer_value
1 through 5, respectively. I would then like to extract 1 as min and 5 as max.
What's the most straightforward way to do this?
Upvotes: 0
Views: 1388
Reputation: 20672
Given an instance integer_market
of IntegerMarket
, you can get all the related Integer
instances using .integers
since you nicely set that as related_name
.
Now you can just do an aggregation using Max
and Min
.
from django.db.models import Max, Min
integer_market.integers.aggregate(Max('integer_value'), Min('integer_value'))
>> {'integer_value__max': 10, 'integer_value__min': 0}
Upvotes: 1
Reputation: 51
Django offers max and min values to be defined in queries.
from django.db.models import Max, Min
Then when defining your query you'll have something like
my_query = models.IntegerMarket.objects.all().annotate(max_integer=Max('integer_value')).annotate(min_integer=Min('integer_value'))
Then you can call those values in your view using max_integer/min_integer or whatever you named it.
Upvotes: 1