How do i use django rest frameworks to serialise a reverse relationship

Question:

I’ve got a Favorites model which keeps track of each users‘ favorite NFT. I want to display the actual NFT data instead of the NFT id. I’m not quite sure how to do so as only primary keys are being returned.

model

class Favorites(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    nft = models.ForeignKey(NFT, on_delete=models.CASCADE)

nft model

class NFT(models.Model):
    address = models.CharField(max_length=42)
    owner_address = models.CharField(max_length=42)
    token_id = models.IntegerField()
    token_URI = models.URLField()
    name = models.CharField(max_length=256)

serializer

class FavoritesSerializer(serializers.ModelSerializer):
    class Meta:
        model = Favorites
        fields = "__all__"

For example, shown in the django rest framework documentation. Instead of having tracks primary keys, I would like to display the actual track model field values

Asked By: Liondancer

||

Answers:

If you inspect that page a little further you will come across this link, and I’ll answer quickly with a reference link as you seem competent enough to understand, whilst I contruct a proper answer.

Nested relationships in django rest framework link:

https://www.django-rest-framework.org/api-guide/relations/#nested-relationships

The documentation describes that to have a relationship rendered by returning certain fields, it is advised that you should create a serialiser for the specific use case, which, in your case

… further answer here which is context specific … I need NFT model please …

For example generically:

class NFTSerialiser(serializers.ModelSerializer):
    pass
    # add your specific fields

And then you can use this serialiser as a field on your Favourite serialiser, specifying the keyword argument many=True

class FavoritesSerializer(serializers.ModelSerializer):
    nft_favourites = NFTSerialiser(many=True, read_only=True)
    class Meta:
        model = Favorites
        fields = "__all__"

Firstly regarding pagination, please read this section of the documentation, it describes how to create your own custom pagination style, should you choose to do this:

https://www.django-rest-framework.org/api-guide/pagination/#modifying-the-pagination-style

For completeness, you may need to, or realise that you need to exclude the NFT_set__id field which is declared implicitly by fields = "__all__" Meta declaration.

Alternatively, I suggest it would be better to declare EXPLICITLY which fields you wish to be rendered.

Answered By: Swift