Home > Mobile >  Django DRF get ForeignKey values in serializer
Django DRF get ForeignKey values in serializer

Time:11-17

I'm trying to retrieve all Benchmarks related to a Node in my serializer, but i'm not too sure how to retrieve them. Would I need to do some sort of reverse foreignkey lookup? Maybe my models are not made correctly?

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 Benchmarks(models.Model):
    benchmark_score = models.IntegerField(default=0)
    benchmarked_at = models.DateTimeField(null=True, blank=True)
    provider = models.ForeignKey(Node, on_delete=models.CASCADE)

class NodeSerializer(serializers.ModelSerializer):

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

CodePudding user response:

You can define a serializer for the Benchmarks model:

class BenchmarkSerializer(serializers.ModelSerializer):
    
    class Meta:
        model = Benchmarks
        fields = ['benchmark_score', 'benchmarked_at']

then we can use that serializer in the NodeSerializer:

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']

Note: normally a Django model is given a singular name, so Benchmark instead of Benchmarks.

CodePudding user response:

Use HyperlinkedModelSerializer like this:

class BenchmarkSerializer(serializers.HyperlinkedModelSerializer):
        
    class Meta:
        model = Benchmarks
        fields = ['benchmark_score', 'benchmarked_at']

class NodeSerializer(serializers.HyperlinkedModelSerializer):
    benchmark_set = BenchmarkSerializer(many=True, read_only=True)

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