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

Time:11-26

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
 }
]

CodePudding user response:

Check if this might help you. it's documentation link for Django-rest-framework

enter image description here

  • Related