I have the following models:
class ContentUpload(BaseModel):
...
status = models.ForeignKey(CourseStatus, on_delete=models.CASCADE, related_name="content_status", null=True, blank = True)
class CourseStatus(BaseModel):
status_name = models.CharField(max_length=250)
slug = models.SlugField()
def save(self, *args, **kwargs):
self.slug = slugify(self.status_name)
super(CourseStatus, self).save(*args, **kwargs)
def __str__(self):
return str(self.status_name)
The following serializers:
class CourseStatusListSerializers(serializers.ModelSerializer):
class Meta:
model = CourseStatus
fields = ('id', 'status_name', 'slug')
def get_status(self, obj):
return CourseStatusListSerializers(obj.status, context={"request": self.context['request']}).data
When the ContentUpload.status is None it returns the following:
"status":{"status_name":"","slug":""}
My question is that how can I do it to give back an empty object? What is your best practice for this?
"status":{}
1- Rewrite your ContentUploadSerializer
to the following:
class ContentUploadSerializer(serializers.ModelSerializer):
status = CourseStatusListSerializers(required=False)
class Meta:
model = ContentUpload
fields = ('id', 'status',)
2- Remove the get_status
method.
The serialized ContentUpload
object with the status
field None
will be as follows:
{
"id": 2,
"status": null
}
And with the status
field not None
it will be:
{
"id": 1,
"status": {
"id": 1,
"status_name": "Pending",
"slug": "pending"
}
}
You can read more about the nested serializers from this page. https://www.django-rest-framework.org/api-guide/serializers/#dealing-with-nested-objects