i have two simple models with random data about phones.
class Phone(models.Model):
name = models.CharField(max_length=200)
description = models.CharField(max_length=400)
image = models.ImageField(upload_to='phone_img/', max_length=255, null=True, blank=True )
slug_phone = models.SlugField(blank=True)
class Price(models.Model):
price = models.DecimalField(max_digits=6, decimal_places=2)
date = models.DateField(null=True, blank=True)
phone = models.ForeignKey(Phone, on_delete=models.CASCADE)
market = models.ForeignKey(Market, on_delete=models.CASCADE)
I am able to send simple data via data the REST_framwork to my API.
views.py
class SnippetList(generics.ListCreateAPIView):
queryset = Price.objects.all()
serializer_class = PriceSerializer
serializers.py
class PriceSerializer(serializers.ModelSerializer):
class Meta:
model = Price
fields = ('id', 'phone', 'price', 'date', 'market', )
phone = serializers.StringRelatedField()
market = serializers.StringRelatedField()
Now i wanted to use the annotate() method with the Min() function in a QuerySet. I wanted to display the minimum price of each phone. So i tried something like this:
views.py
from django.db.models import Min
<....>
class SnippetList(generics.ListCreateAPIView):
queryset = Price.objects.all()
serializer_class = PriceSerializer
def get_queryset(self):
min_price = Phone.objects.annotate(Min('price__price'))
return min_price
of course this did not work. i followed along the server errors messages and ended with this:
serializers.py
from rest_framework import serializers
from market.models import Price, Phone
class PriceSerializer(serializers.ModelSerializer):
class Meta:
model = Price
fields = ('id', 'phone', 'price', 'date', 'market')
class Meta:
model = Phone
fields = ('name', 'phone', 'market', )
phone = serializers.StringRelatedField()
market = serializers.StringRelatedField()
My API shows me now this output, it´s not the min_price value, but at least something:
{"count":7,"next":null,"previous":null,"results":[{"name":"SAMSUNG Galaxy S10"},{"name":"SAMSUNG Galaxy S10 plus"},{"name":"SAMSUNG Galaxy S10e"},{"name":"SAMSUNG Galaxy S8"},{"name":"SAMSUNG Galaxy S8 Plus"},{"name":"SAMSUNG Galaxy S9"},{"name":"SAMSUNG Galaxy S9 plus"}]}
So i asked myself where to put .annotate(Min ? Or should i created a single ListCreateAPIView with queryset = Phone.objects.all() ? Is it possible to display the data of min_price without a new field in my serializers.py?
Pricemodel, it won't return an expected result. Because, each row has only onepriceattribute, hence theMin(price)becomepriceitself.