【问题标题】:DRf, paginate foreign key fieldDRf,分页外键字段
【发布时间】:2019-09-21 02:37:16
【问题描述】:

我想做下面这样的事情,但是代码效率低下,

如何返回相关对象的分页响应?

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)

【问题讨论】:

    标签: django django-rest-framework


    【解决方案1】:

    其实我在这里找到了答案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 representation
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-16
      • 2021-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-17
      • 2017-05-24
      相关资源
      最近更新 更多