Cross-table serialization Django REST Framework

丶灬走出姿态 提交于 2019-12-07 00:12:35

DRF serializers can do two things:

  1. Serialize complex data (such as querysets) to native Python datatypes

    serializer = CommentSerializer(comment)
    serializer.data
    # {'email': u'leila@example.com', 'content': u'foo bar', 'created': datetime.datetime(2012, 8, 22, 16, 20, 9, 822774)}
    
  2. Deserialize data from native Python datatypes

    serializer = CommentSerializer(data=data)
    serializer.is_valid()
    # True
    serializer.validated_data
    # {'content': 'foo bar', 'email': 'leila@example.com', 'created': datetime.datetime(2012, 08, 22, 16, 20, 09, 822243)}
    

In your case where

All I want is to return all article pub_dates and their corresponding article coordinates lat/long's (from the pointField).

You will have to do two things:

  1. Create a complex data structure using either an object, a list of objects or a queryset.

    In your case this is pretty easy, you just need a queryset with all articles and with prefetched locations in order to prevent unnecessary db hits for each location.

    Article.objects.all().prefetch_related('locations')[:10]
    
  2. Create a serializer which can serialize this queryset.

    Since you have nested data structure (one article can have many locations) you better split this into two separate serializers.

    The first one will know how to serialize locations only, and the second one will know how to serialize articles only, but it will use the first one for the article.locations serialization.

    class LocationSerializer(serializers.ModelSerializer):
        class Meta:
            model = Location
            fields = ('point',)
    
    
    class ArticleSerializer(serializers.ModelSerializer):
        #this way we override the default serialization 
        #behaviour for this field.
        locations = LocationSerializer(many=True)
    
        class Meta:
            model = Article
            fields = ('pub_date', 'locations')
    

Finally you can combine 1 and 2 via a ViewSet

class ArticleViewSet(viewsets.ModelViewSet):
    serializer_class = ArticleSerializer
    #read about pagination in order to split this into pages
    queryset = Article.objects.all().prefetch_related('locations')[:10]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!