只返回序列化程序中相关模型的最后一个条目 - Django

时间:2015-10-31 13:48:23

标签: python json django serialization django-rest-framework

我有两个Django模型,讨论和发布设置如下:

讨论模式:

class Discussion(models.Model):
    Discussion_ID = models.AutoField(primary_key=True)
    Topic = models.CharField(max_length=50)
    Group = models.ForeignKey(Group, related_name="Group_Discussions")

    class Meta:
        db_table = "Discussions"        

发布模型:

class Post(models.Model):
    Post_ID = models.AutoField(primary_key=True)
    Date_Posted = models.DateTimeField(auto_now_add=True)
    Discussion = models.ForeignKey(Discussion, db_column="Discussion_ID", related_name="Posts")
    User = models.ForeignKey(User, related_name="User_Posts")
    Message = models.TextField()

    class Meta:
        db_table = "Posts"

我想序列化所有讨论的列表,并且在序列化程序中,仅包括每个讨论的最新帖子。到目前为止,我的序列化器看起来像这样:

class DiscussionSerializer(serializers.ModelSerializer):
    last_post = serializers.SerializerMethodField()
    post_count = serializers.SerializerMethodField()

    class Meta:
        model = Discussion
        fields = ('Discussion_ID', 'Topic', 'last_post', 'post_count')

    def get_last_post(self, obj):
        return Post.objects.raw("SELECT * FROM Posts WHERE Discussion_ID = %s ORDER BY Post_ID DESC LIMIT 1" % obj.Discussion_ID)

    def get_post_count(self, obj):
        return obj.Posts.count()

不幸的是,这会返回以下错误,我不确定还有什么可以尝试:

<RawQuerySet: SELECT * FROM Posts WHERE Discussion_ID = 1 ORDER BY Post_ID DESC LIMIT 1> is not JSON serializable

基本上,我想将讨论模型与讨论中的最新帖子序列化为JSON,如下所示:

{ 
    "Discussion_ID": 1, 
    "Topic": "Some topic",
    "last_post": { 
        "Post_ID": 1,
        "Date_Posted": "...",
        "Discussion": 1,
        "User": 1,
        "Message": "This is a message"
    },
    "post_count": 10
}

2 个答案:

答案 0 :(得分:1)

我设法使用以下内容:

def get_last_post(self, obj):
    try:
        post = obj.Posts.latest('Date_Posted')
        serializer = PostSerializer(post)
        return serializer.data
    except Exception, ex:
        return None

虽然感觉有点哈哈,所以我仍然愿意接受其他解决方案。

答案 1 :(得分:0)

要改进您的解决方案,您可能希望将此代码移动到viewset方法并处理其他一些内容,例如权限,应用Posts的过滤器(如果有的话)和“未找到”错误。例如:

class PostViewSet(viewsets.GenericViewSet, mixins.RetrieveModelMixin):

    #...

    def retrieve_last():

        queryset = self.filter_queryset(self.get_queryset())

        try:
            obj =  queryset.latest('Date_Posted')
        except queryset.model.DoesNotExist:
            raise Http404('No %s matches the given query.' \
                          % queryset.model._meta.object_name)

        self.check_object_permissions(self.request, obj)

        serializer = self.get_serializer(obj)

        return Response(serializer.data)

顺便说一句,这是受到DRF ModelViewSet的启发。