gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 18:34:58 27 4
gpt4 key购买 nike

我有两个 Django 模型,Discussion 和 Post 设置如下:

讨论模式:

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
}

最佳答案

我设法通过以下方式实现了这一点:

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

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

关于python - 仅返回序列化程序中相关模型的最后一个条目 - Django,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33452330/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com