0xcurb
0xcurb

Reputation: 126

Retrieve related field detail instead of id

I have a model like this>

class Orders(models.Model):
 ....
 status = models.ForeignKey('Status')

class Status(models.Model):
 status_name = models.CharField(max_length=CHARFIELD_MAX_LEN)

And in my views I make a query like this>

all_orders = Orders.objects.all()
resp = serializers.serialize('json', all_orders)

But what I need is to get the status name instead of the status id stored in the orders table, how can that be done?

Upvotes: 0

Views: 67

Answers (2)

Rohan
Rohan

Reputation: 53336

You can do that using natural keys. You need to define natural_key() method in Status model and pass use_natural_foreign_keys=True.

class Orders(models.Model):
   ....
   status = models.ForeignKey('Status')

class Status(models.Model):
    status_name = models.CharField(max_length=CHARFIELD_MAX_LEN)
    #def natural_key(self):
        return (self.status_name,)

Then to serialize objects

all_orders = Orders.objects.all()
resp = serializers.serialize('json', all_orders, use_natural_foreign_keys=True)

Upvotes: 1

ruddra
ruddra

Reputation: 51988

according to here:

all_orders= Orders.objects.all().values_list('status__status_name')

It will get the list of status name

Upvotes: 0

Related Questions