Home > OS >  Django DRF foreignkey serializer - how to return only the latest object?
Django DRF foreignkey serializer - how to return only the latest object?

Time:11-19

I currently have to models where a Node can have many Benchmark's, but when displaying it to the end users, I only want the serializer to return the latest benchmark for the node, instead of all of them which it currently does. How can I do this?

Models.py

class Node(models.Model):
    node_id = models.CharField(max_length=42, unique=True)
    wallet = models.CharField(max_length=42, null=True, blank=True)
    earnings_total = models.FloatField(null=True, blank=True)
    data = models.JSONField(null=True)
    online = models.BooleanField(default=False)
    version = models.CharField(max_length=5)
    updated_at = models.DateTimeField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)


class Benchmark(models.Model):
    benchmark_score = models.IntegerField()
    benchmarked_at = models.DateTimeField(default=timezone.now)
    provider = models.ForeignKey(Node, on_delete=models.CASCADE)

serializers.py

class BenchmarkSerializer(serializers.ModelSerializer):

    class Meta:
        model = Benchmark
        fields = ['benchmark_score', 'benchmarked_at']


class NodeSerializer(serializers.ModelSerializer):
    benchmark_set = BenchmarkSerializer(many=True)

    class Meta:
        model = Node
        fields = ['earnings_total', 'node_id', 'data',
                  'online', 'version', 'updated_at', 'created_at', 'benchmark_set']

CodePudding user response:

You can use SerializerMethodField to have this result :

class NodeSerializer(serializers.ModelSerializer):
    last_benchmark = SerializerMethodField('get_benchmark')

    class Meta:
        model = Node
        fields = ['earnings_total', 'node_id', 'data',
              'online', 'version', 'updated_at', 'created_at', 'last_benchmark ']

    def get_benchmark(self, node):
        benchmark = Benchmark.objects.last()
        serializer = BenchmarkSerializer(instance=benchmark , many=True)
        return serializer.data

To resume, you create a new field in the serializer that return the latest benchmark object serialized with BenchmarkSerializer.

  • Related