Eucrow
Eucrow

Reputation: 47

serializer only certain fields in foreing key relation

I'm trying to serializer two nested models linked by a foreing key:

class Category(models.Model):
    sp = models.ForeignKey('species.Sp', on_delete=models.CASCADE, related_name='species_category')
    category_name = models.CharField(max_length=50)

class Catch(models.Model):
    weight = models.IntegerField()
    category = models.ForeignKey('species.Category', on_delete=models.CASCADE,)

I know is possible to use depth option, but it serialize all the fields of the related model, for example:

class CatchesSerializer(serializers.ModelSerializer):
    class Meta:
        model = Catch
        fields = ['id', 'weight', 'category', ]
        depth = 1

returns

[
    {
        "id": 335,
        "weight": 4710,
        "category": {
            "id": 1,
            "category_name": "1",
            "sp": 41
        }
    },
...
]

How is the way to serialize only certains fields of the related model? for example:

[
    {
        "id": 335,
        "weight": 4710,
        "category": {
            "sp": 41,
        }
    },
...
]

Upvotes: 1

Views: 40

Answers (1)

minglyu
minglyu

Reputation: 3327

Serializer can be nested, you can try:

class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = ['sp']

class CatchesSerializer(serializers.ModelSerializer):
    category = CategorySerializer()

    class Meta:
        model = Catch
        fields = ['id', 'weight', 'category']

Upvotes: 1

Related Questions