Django-Rest-Framework - nested objects and serializers, how to? -


i'm using drf first time. i've been reading documentation pages no clue on how this.

i have 2 models, adprice model make reference ad model. need list various prices ad.

my question is: how can list of ads this?

[     {     "title": "some long title ad1",     "name": "name ad1",     "prices": {                   { "name": "price now", "price": 200 },                    { "name": "price later", "price": 300 }               }     }, ] 

models.py

class ad(models.model):     title = models.charfield(max_length=250)     name = models.charfield(max_length=100)      def __str__(self):         return self.name  class adprice(models.model):     ad = models.foreignkey(ad)     name = models.charfield(max_length=50)     price = models.decimalfield(max_digits=6, decimal_places=2)      def __str__(self):         return self.name 

serializers.py

class adpriceserializer(serializers.serializer):     name = serializers.charfield(max_length=50)     price = serializers.decimalfield(max_digits=6, decimal_places=2)      class meta:         model = adprice  class adserializer(serializers.serializer):     title = serializers.charfield(max_length=250)     name = serializers.charfield(max_length=100)     prices = adpriceserializer(many=true) 

views.py

class adviewset(viewsets.modelviewset):     """     api endpoint allows users viewed or edited.     """     queryset = ad.objects.all().order_by('-date_inserted')     serializer_class = adserializer 

when try code above got error:

attributeerror @ /ads/  got attributeerror when attempting value field `prices` on serializer `adserializer`. serializer field might named incorrectly , not match attribute or key on `ad` instance. original exception text was: 'ad' object has no attribute 'prices'. 

any clues on how solve this?

best regards, andré lopes.

from seeing here you're missing read_only=true , class meta within

class adserializer(serializers.serializer):     title = serializers.charfield(max_length=250)     name = serializers.charfield(max_length=100)     prices = adpriceserializer(many=true, read_only=true)      class meta:         model = ad 

and in order avoid n+1 query problem you'd want override queryset

from django.db.models import prefetch

queryset=ad.objects.all().order_by('-date_inserted').prefetch_related(prefetch('adprice_set', queryset=adprice.objects.filter(ad_id__in=queryset), to_attr='prices')) 

since django has lazy orm, means every ad have in there, make query adprices. 100 ads, make 200 queries. not efficient solution, right?. prefetch you're making short 2 queries, 1 ads , other 1 relevant adprices.


Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -