在Serializer中高效计算相关对象:Django Rest Framework

时间:2015-09-18 04:41:43

标签: django django-rest-framework serializer

我有一个具有递归关系的模型:

class Update(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    creator = models.ForeignKey(settings.AUTH_USER_MODEL)
    update = models.CharField(max_length=140, null=True, blank=True)
    featured = models.BooleanField(default=False)
    response = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL, related_name='responding_update')

我尝试对其进行序列化,以便它还返回特定更新的响应数。

class UpdateSerializer(serializers.ModelSerializer):
    replies = ReplyCountSerializer(read_only=True)

    class Meta:
        model = Update

class ReplyCountSerializer(serializers.RelatedField):

    def to_representation(self, instance):
        count = ??? Number of responses to the Update ???
        return count

实现我所寻找的最便宜的方式是什么?

0 个答案:

没有答案