1
我想知道以下是否可能,以及是否有人可以解释如何。我正在使用Django REST FrameworkDjango:在所有查询集对象上运行方法
我有一个模型,在该模型中我有一个类叫做产品。产品具有称为的方法is_product_safe_for_user。它需要用户对象和自我(产品)。
model.py
class Product(models.Model):
title = models.CharField(max_length=60, help_text="Title of the product.")
for_age = models.CharField(max_length=2,)
def is_product_safe_for_user(self, user):
if self.for_age > user.age
return "OK"
(忽略上面的语法,它只是给你一个想法)
我想要做的就是运行的方法,对所有查询集对象,像下面的东西,但我不知道如何...
class ProductListWithAge(generics.ListAPIView):
permission_classes = (permissions.IsAuthenticated,)
model = Product
serializer_class = ProductSerializer
def get_queryset(self):
Product.is_product_safe_for_user(self,user)
# then somehow apply this to my queryset
return Product.objects.filter()
还会有一些时候,我想只在一个对象上运行methoud。
还是应该进入串行器?如果是的话怎么办?...
class ProductSerializer(serializers.ModelSerializer):
safe = serializers.Field(Product='is_product_safe_for_user(self,user)')
class Meta:
model = Product
fields = ('id', 'title', 'active', 'safe')
这样就意味着,如果我打印出的所有产品,我会为每个item.onlysafeobjects?我怎么会通过用户(这是通过我的网址) – Prometheus 2013-02-15 22:48:07
该示例演示如何传递用户。自定义管理器就像整个表格的过滤器。您使用管理器访问的内容已经过滤。你应该阅读我链接的文档,以便更好地了解管理者是什么。 – 2013-02-15 22:49:24