Search code examples
django-rest-frameworkdjango-serializer

Django DRF Serializer StringRelatedField not returning null


I need a StringRelatedField to return null when there is a null value.

These are the models

class Category(models.Model):
    name = models.CharField(max_length=100 )

class Task(models.Model):
    task_name = models.CharField(max_length=140)
    category = models.ForeignKey(Category, related_name='categories', null=True, blank=True, on_delete=models.PROTECT)

This is the serializer

class TaskSerializer(serializers.ModelSerializer):
    category_name = serializers.StringRelatedField(source='category.name')

    class Meta:
        model = Task
        fields = [
        'task_name',
        'category',  
        'category_name',
          ]

Current Results

When 'category' id not null, the correct data is returned

{
    "task_name": "123",
    "category": 1,
    "category_name": django,
}

With 'category' id null the 'category_name' is not returned.

{
    "task_name": "123",
    "category": null,
}

Required Results

When 'category' id null still return "category_name" as null.

{
    "task_name": "123",
    "category": null,
    "category_name": null,
}

Solution

  • I think all serializers can have parameter allow_null so in your case it will look like:

    class TaskSerializer(serializers.ModelSerializer):
        category_name = serializers.StringRelatedField(source='category.name', allow_null=True)
    
        class Meta:
            model = Task
            fields = [
            'task_name',
            'category',  
            'category_name',
        ]