Reputation: 425
recently i started on django framework and i am stuck at this situation tried reading documentation but my lack of experience i am not able understand much is there any way we can get response how we wanted with keeping django default checks,validation as much as possible. i tried using def to_representation but still it's giving me reponse as null when i debug.
use case: i have mention model below i want foreign key value as text what stored in table status_lookup.name from product table
class product_serializer(serializers.ModelSerializer):
status = status_lookup_serializer(read_only=True,many=False)
class Meta:
model = product
fields = ('id','name','status_id','status')
model.py
class status_lookup(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=30)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(blank=True)
activation_date = models.DateTimeField(auto_now_add=True)
deactivation_date = models.DateTimeField(blank=True,default=None)
def __str__(self):
return self.name
class product(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=30)
img_url = models.CharField(max_length=255,blank=True)
status_id = models.ForeignKey(status_lookup, related_name='status', on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(blank=True)
activation_date = models.DateTimeField(auto_now_add=True)
deactivation_date = models.DateTimeField(blank=True,default=None)
def __str__(self):
return self.name
I want
[
{
"id":1,
"name":"xxx",
"status":pending
}
]
Upvotes: 2
Views: 175
Reputation: 425
I was able to do it with this I dunno if it's the optimal way to do it or not but will keep this question open until I found one or someone answer.
class statusField(serializers.RelatedField):
def to_representation(self, value):
return {
'name':value.name
}
class product_serializer(serializers.ModelSerializer):
status_id = statusField(many=False,read_only=True)
class Meta:
model = product
fields = ('id','name','status_id')
Upvotes: 2
Reputation: 39
Check if this might help you. it's documentation link for Django-rest-framework
https://www.django-rest-framework.org/api-guide/serializers/
Upvotes: 2