我想做一些类似下面的事情,但是代码效率很低,
如何返回相关对象的分页响应?
class Bar(models.Model):
pass
class Foo(models.Model):
bar = models.ForeignKey('bar')
foo_id = request.data.get('foo_id')
foos = Foo.objects.get(id=foo_id)
bars = [
foo.bar
in
foo
for
foos
]
page = self.paginate_queryset(bars)
serializer = BarSerializer(page, many=True)
return self.get_paginated_response(serializer.data)发布于 2019-09-21 10:43:55
实际上我在这里找到了答案https://stackoverflow.com/a/37657376/433570
想法是将嵌套的对象展平
class FooSerializer():
bar = BarSerializer()
def to_representation(self, obj):
"""Move fields from profile to user representation."""
representation = super().to_representation(obj)
profile_representation = representation.pop('bar')
for key in profile_representation:
representation[key] = profile_representation[key]
return representationhttps://stackoverflow.com/questions/58036836
复制相似问题