Reputation: 726
My models:
class Product(models.Model):
name = models.CharField(max_length=125, blank=False, null=False)
description = models.CharField(max_length=255, blank=True)
abbreviation = models.CharField(max_length=15, blank=True)
category = models.ForeignKey('inventory.Category',
on_delete=models.SET_NULL, null=True, blank=True)
metric = models.CharField(max_length=15, blank=True, null=True)
class Category(models.Model):
name = models.CharField(max_length=55, blank=False, null=False)
abbreviation = models.CharField(max_length=15, blank=True)
parent_category = models.ForeignKey('inventory.Category',
on_delete=models.SET_NULL, null=True, blank=True)
I want to recover all products:
products = Product.objects.all()
That's ok. I get all the products with success.
But I want that the products returned came with the ForeignKey attribute as an textual field from the referenced model, and no the raw integer that references it.
The field in question would be the Category.name.
At present my return is:
{model: product, pk:1, fields: {..., category: 1} }, { ....... } ...
What I Want:
{model: product, pk:1, fields: {..., category: 'Categoria 1 '}
I need the set pre-populated with the related model info, cause I'll return a JSON string as result for the service caller.
My attempt to return JSON:
products = Product.objects.all()
serialized_products = serializers.serialize('json', products)
return JsonResponse({'result': 'success', 'data':serialized_products}) #return all
How can I do this? The most simple and elegant form...
Upvotes: 2
Views: 315
Reputation: 25539
The only thing I can think of is use values_list
to return whatever fields you want:
products = Product.objects.all().values('name',
'description',
'category__name',
'category__id',
'category__abbreviation')
return JsonResponse(products)
It might be a little less convenient then serializer, but I don't think serializer is good at handling foreigne key relations because what if you have deeper relationships that you need to include in the result?
Upvotes: 1