【发布时间】:2013-02-02 00:18:43
【问题描述】:
我有以下使用Django REST Framework 的序列化程序。
这就是我目前所拥有的......
serializer.py
class ProductSerializer(serializers.ModelSerializer):
score = serializers.SerializerMethodField('get_this_score')
class Meta:
model = Product
fields = ('id', 'title', 'active', 'score')
def get_this_score(self, obj):
profile = Profile.objects.get(pk=19)
score = [val for val in obj.attribute_answers.all() if val in profile.attribute_answers.all()]
return (len(score))
urls.py
url(r'^products/(?P<profile_id>.+)/$', ProductListScore.as_view(), name='product-list-score'),
这段代码的 sn-p 存在一些问题。
1) 婴儿车 pk=19 是硬编码的,它应该是 self.kwargs['profile_id']. 我已经尝试过并尝试过,但我不知道如何将 kwarg 传递给方法并且无法让 profile_id 工作。即我无法从 url 获取它。
2) 这些代码是否应该在模型中?我已经尝试添加到模型,但再次可以传递参数。
models.py 即方法类
def get_score(self, profile):
score = [val for val in self.attribute_answers.all() if val in
profile.attribute_answers.all()]
return len(score)
【问题讨论】:
标签: django django-models django-rest-framework