仅返回序列化器中相关模型的最后一个条目-Django [英] Return only last entry of related model in serializer - Django

查看:86
本文介绍了仅返回序列化器中相关模型的最后一个条目-Django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have two Django models, Discussion and Post set up as follows:

讨论模型:

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"

我要序列化所有讨论的列表,并在序列中大小,仅包含每个讨论的最新帖子。到目前为止,我的序列化程序如下所示:

I want to serialize a list of all discussions, and in the serializer, include ONLY the latest post for each discussion. So far, my serializer looks like this:

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()

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

Unfortunately, this return the following error and I'm not quite sure what else to try:

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

基本上,我想对讨论模型以及讨论中的最新帖子进行序列化变成看起来像这样的JSON:

Basically, I want to serialize the Discussion model along with the lastest post in the discussion into JSON that looks something like this:

{ 
    "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
}


推荐答案

我设法通过以下方法使之工作:

I managed to get this working with the following:

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

虽然感觉有点,所以我仍然对其他解决方案持开放态度。

It feels a bit hacky though so I am still open to other solutions.

这篇关于仅返回序列化器中相关模型的最后一个条目-Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆