结合DRF无关模型

时间:2017-11-26 17:58:36

标签: django django-rest-framework

我似乎无法弄清楚这一点。我想按用户加入时间和用户的照片时间排序。

views.py

class UserExploreAPIView(generics.ListAPIView):
    """
    User explore API view.
    """
    serializer_class = TimelineSerializer
    permission_classes = (IsAuthenticated,)
    pagination_class = SmallResultsSetPagination

    def get_queryset(self):
        merged_queryset = Places.get_explore_queryset(self.request.user)
        queryset = Places.objects.filter(pk__in=merged_queryset)
        ann_user = User.objects.annotate(photo_time=Extract('date_joined','epoch'))
        return list(chain(ann_user, queryset))

serializers.py

class SomeUserModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = SomeUserModel
        fields = ('photo','id')

class PlacesSerializer(serializers.ModelSerializer, IdFieldMixin):
    photo_link = serializers.CharField(read_only=True)
    user =  UserRelatedSerializer()

    class Meta:
        fields = ['id', 'user']
        model = Places

class TimelineSerializer(serializers.Serializer):     
    photo_time = serializers.CharField(read_only=True)
    places= PlacesSerializer() #this is the error
    someuser= SomeUserModelSerializer()

    class Meta:
        fields = ['photo_time', 'someuser','places']
        ordering = ('photo_time')

当我尝试places时,User没有属性places。嗯,是。 places对用户来说是一个外键,用户不会只有相反的位置。我如何组合这两个模型? SomeUserModel有效,因为onetoone与用户有关,但它不能与places一起使用。

更新:随时间添加

class TimelineItemSerializer(serializers.Serializer):
    time = serializers.CharField(read_only=True)
    places= PlacesSerializer() #this is the error
    someuser= SomeUserModelSerializer()

class TimelineSerializer(serializers.Serializer):     
    time = TimelineItemSerializer()

    class Meta:
        fields = '__all__'
        order_by  = ('time')

更新

json ={
time: 1511654400,
{
   modelA: {'atter1, atter2, atter3}
   modelB: {'atter1, atter2, atter3}
},
time:1511136000, 
{
   modelA: {'atter1, atter2, atter3} # could be empty
   modelB: {'atter1, atter2, atter3}
}
}

0 个答案:

没有答案