我正在序列化一个 Product 模型及其注释。这是我的简单代码:
class ProductSerializer(serializers.HyperlinkedModelSerializer):
comment_set = CommentSerializer(many=True, read_only=True)
class Meta:
model = Product
fields = [
'title',
'comment_set'
]
class CommentSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Comment
fields = [
'text',
]
class Comment(models.Model):
product = models.ForeignKey(Product, null=True, blank=True, db_index=True)
class Product(models.Model):
title = models.CharField(max_length=50)
...
问题:
如果产品有很多评论。例如,500 条评论。其中 500 篇都被连载了。
如何将结果限制为我自己选择的数量,例如 100 条评论?
我在发布之前做了一些研究,但只发现了关于过滤的问题。
谢谢你。
最佳答案
在 Product
上定义一个新方法返回具有有限评论数量的查询集的模型。
然后将该方法作为 CommentSerializer
的源传递在您的 ProductSerializer
内.
class Product(models.Model):
title = models.CharField(max_length=50)
def less_comments(self):
return Comment.objects.all().filter(product=self).order_by("-id")[:100]
然后在
ProductSerializer
:class ProductSerializer(serializers.HyperlinkedModelSerializer):
comment_set = CommentSerializer(many=True, read_only=True, source="less_comments")
PS:凭内存写代码,没有测试它们。但应该工作。
关于django - 在 Django Rest Framework 中,如何限制序列化的外键对象数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38289324/