conol
conol

Reputation: 425

How can i get foreign key table value istead of id in Django rest_framework?

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

o/p enter image description here

I want

[
 {
  "id":1,
  "name":"xxx",
  "status":pending
 }
]

Upvotes: 2

Views: 175

Answers (2)

conol
conol

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')

enter image description here

Upvotes: 2

Cornal
Cornal

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

Related Questions