Python 仅返回serializer-Django中相关模型的最后一个条目
我有两个Django模型,讨论和发布设置如下: 讨论模式:Python 仅返回serializer-Django中相关模型的最后一个条目,python,json,django,serialization,django-rest-framework,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:
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()
{
"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
}
不幸的是,这将返回以下错误,我不太确定还要尝试什么:
<RawQuerySet: SELECT * FROM Posts WHERE Discussion_ID = 1 ORDER BY Post_ID DESC LIMIT 1> is not JSON serializable
我通过以下方式实现了这一目标:
def get_last_post(self, obj):
try:
post = obj.Posts.latest('Date_Posted')
serializer = PostSerializer(post)
return serializer.data
except Exception, ex:
return None
虽然感觉有点黑客,但我仍然对其他解决方案持开放态度。要改进您的解决方案,您可能需要将此代码移动到viewset方法,并处理一些其他问题,如权限、为
帖子应用过滤器(如果有)和“未找到”错误。例如:
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
启发的