【问题标题】:How to limit number of records in Django Rest Framework reverse relations如何限制 Django Rest Framework 反向关系中的记录数
【发布时间】:2014-03-21 03:24:33
【问题描述】:

我开始使用 Django Rest Framework,它的表现非常好。我让所有的东西都按照我想要的方式工作。我遇到了一个我没有得到答案的问题。

我正在使用反向关系。

型号

class Province(models.Model):
    name = models.CharField(max_length=50)
    intro = models.CharField(max_length=1000, null=True, blank=True)
    description = models.TextField(max_length=10000, null=True, blank=True)

class Picture(models.Model):
    name = models.TextField("Title", max_length=10000, null=True, blank=True)
    pro = models.ForeignKey(Province, verbose_name="Province")

当我编写省的反向关系序列化程序时,例如一个省。

观看次数

ProToPicturesSerial(node, many=False).data

我得到了这个省所有的pictures。我想获取一些图片,可能是最近的 3 张,或者最近添加的 5 张图片。

如何限制图片实例的数量?因为随着图片记录中数量的增加,应用程序将趋于变慢。

序列化器

class ProToPicturesSerial(serializers.ModelSerializer):
    pro_pictures = PictureSerializer(many=True)

    class Meta:
        model = Province
        fields = ('id', 'name', 'intro', 'description', 'pro_pictures')

如果我遗漏了一些明显的东西,请告诉我。

【问题讨论】:

    标签: json django api rest django-rest-framework


    【解决方案1】:

    您可以将PictureSerializersource 属性指向一个只返回3 张相关图片的省方法:

    class ProToPicturesSerial(serializers.ModelSerializer):
        pro_pictures = PictureSerializer(many=True, source='first_three_pics')
    
        class Meta:
            model = Province
            fields = ('id', 'name', 'intro', 'description', 'pro_pictures')
    

    class Province(models.Model):
        name = models.CharField(max_length=50)
        intro = models.CharField(max_length=1000, null=True, blank=True)
        description = models.TextField(max_length=10000, null=True, blank=True)
    
        def first_three_pics(self):
            return self.picture_set.all()[:3]
    

    【讨论】:

    • 谢谢,我会看看这个。
    • 但是前三张图片的排列顺序的依据是什么?主键?如果是,它是自动升序还是降序?
    • @BilliAm 您可以在查询中使用 order_by 来控制项目顺序,例如self.picture_set.all().order_by('-created_date')[:3] 或者使用模型元排序属性....docs.djangoproject.com/en/1.7/ref/models/querysets/…
    猜你喜欢
    • 2012-12-25
    • 1970-01-01
    • 2018-08-04
    • 2015-12-14
    • 2013-10-20
    • 2017-10-05
    • 2015-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多