whitebear
whitebear

Reputation: 12445

Serializer for fetchiing data from multiple classes

Environment is Python and Django3

I want to make api which retrieve the data from multiple model class.

I have models like this , each CountryStat has Country.

class Country(models.Model):
    code = models.CharField(max_length=3,unique=True)
    name = models.CharField(max_length=50)

class CountryStat((models.Model):
    country = models.ForeignKey(Country, on_delete=models.CASCADE,null=True)
    date = models.DateField(null=True,blank =True)
    stat = models.IntegerField()

Now I want to get the latest Coutry Stat for each Country.

So I made the serializer for Country

class CountrySerializer(serializers.ModelSerializer): 
    latest_stat = serializers.SerializerMethodField()
    class Meta:
        model = Country
        fields = ('id','code','latest_stat')
    def get_latest_stat(self,obj):
        # how can I get the latest stat from CountryStat model ????

Is this the correct idea or how can I make it??

Upvotes: 1

Views: 28

Answers (1)

GProst
GProst

Reputation: 10237

You should define a custom latest_stat attribute on your model:

class Country(models.Model):
  code = models.CharField(max_length=3,unique=True)
  name = models.CharField(max_length=50)  
  
  def latest_stat(self):
    return self.countrystat_set.order_by('-date').first()

Upvotes: 1

Related Questions