django rest framework – ensure foreignKey field is optional [SOLVED]

I am using ModelSerializers and faced hardtime ensuring foreign key could be optional:

models.py:

class Tag(models.Model):
label = models.CharField(max_length=100)
group = models.ForeignKey(TagGroup, null=True, blank=True, related_name='tags'

class TagGroup(models.Model):
label = models.CharField(max_length=100)

serializers.py:

class TagSerializer(serializers.ModelSerializer):
class Meta:
model = Tag
fields = ('id', 'label', 'group')
group = TagGroupSerializer()

class TagGroupSerializer(serializers.ModelSerializer):
class Meta:
model = TagGroup
fields = ('id', 'label',)

With above setup, though foreignKey field is clearly defined as nullable and not-mandatory in models.py, i kept getting following error:

‘{“group”:[“This field may not be null.”]}’

Reason for this is that you also need to specify field as nullable and non-mandatory in the serializer!
Below change solved the issue:

group = TagGroupShortestSerializer(required=False, allow_null=True)

Post a Comment

Your email is never published nor shared. You're allow to say what you want...