How can i Get foreign key's value instead of id , in django rest framework -
sorry bad english hope u can understand mean.
out put im getting now:
[ { "maincatname": 1, "name": "harry potter", "image": "/media/101029496--sites-default-files-images-101029496-3176173-1748009911-hp.jp-1_moxqrlp.jpg" }, { "maincatname": 2, "name": "princes girl", "image": "/media/character_princess_rapunzel_8320d57a.jpeg" }, { "maincatname": 3, "name": "sex in city", "image": "/media/250px-satc_title.jpg" }, { "maincatname": 4, "name": "who dragon", "image": "/media/reggio_calabria_museo_nazionale_mosaico_da_kaulon.jpg" }, { "maincatname": 2, "name": "drama queen", "image": "/media/15241421_170761763390015_7913498865987146084_n.jpg" } ]
what want :
want to return forign key's (maincatname) value in table instead of id. ie value in [categoryname = models.charfield(max_length=50)] in models.py
like
[ { "maincatname": story books, "name": "harry potter", "image": "/media/101029496--sites-default-files-images-101029496-3176173-1748009911-hp.jp-1_moxqrlp.jpg" }, { "maincatname": darama, "name": "princes girl", "image": "/media/character_princess_rapunzel_8320d57a.jpeg" }, { "maincatname": roamance, "name": "sex in city", "image": "/media/250px-satc_title.jpg" }, { "maincatname": sex, "name": "who dragon", "image": "/media/reggio_calabria_museo_nazionale_mosaico_da_kaulon.jpg" }, { "maincatname": darama, "name": "drama queen", "image": "/media/15241421_170761763390015_7913498865987146084_n.jpg" } ]
here code :
veiws.py :
class getcatveiw(apiview): def get(self, request): data = products.objects.only('maincatname','name','image') serializer = getcat(data, many=true) return response(serializer.data) def post(self): pass
models.py :
class category(models.model): categoryname = models.charfield(max_length=50) class meta: verbose_name_plural = 'categories' def __str__(self): return self.categoryname class products(models.model): maincatname = models.foreignkey(category, on_delete=models.cascade) name = models.charfield(max_length=50) image = models.imagefield() price = models.integerfield() discriptionheading = models.charfield(max_length=100) discriptionparagraph = models.textfield(max_length=1000) class meta: verbose_name_plural = 'products' def __str__(self): return str(self.maincatname)+' - '+self.name+' - '+str(self.price)+' $'
serializers.py :
class getcat(serializers.modelserializer): class meta: model = products fields = ('maincatname', 'name', 'image')
you have slugrelatedfield
that:
class getcat(serializers.modelserializer): maincatname = serializers.slugrelatedfield(read_only=true, slug_field='categoryname') class meta: model = products fields = ('maincatname', 'name', 'image')
edit: i'm not sure it'll work products.objects.only('maincatname','name','image')
you'll span database relation. you'll want use select_related
avoid getting n+1 db query.
Comments
Post a Comment