pythonpython-3.xdjango-rest-frameworkswaggerdrf-yasg

Query parameter setting with Swagger


How can I change the required fields (address, token_id, etc) to not be required like limit and offset in swagger?

This is specific for GET requests

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 NFTSerializer(serializers.ModelSerializer):
    class Meta:
        model = NFT
        fields = [
            "address",
            "owner_address",
            "token_id",
            "token_URI",
            "name",
        ]

enter image description here


Solution

  • Since drf-yasg follows the serializer definition, you can add required=False in the serializer

    class NFTSerializer(serializers.ModelSerializer):
    
        address = serializers.CharField(required=False)
        token_id = serializers.IntegerField(required=False)
    
        class Meta:
            model = NFT
            fields = [
                "address",
                "owner_address",
                "token_id",
                "token_URI",
                "name",
            ]