Django Rest Framework - 模型方法中的self.request.user

时间:2018-02-03 15:08:17

标签: python django django-rest-framework

我有一个模特:

User是来自django.contrib.auth.models

的django用户模型
# drink/models.py
class Drink(models.Model):
    name = models.CharField(max_length=32)
    bartender = models.ForeignKey('bartender.Bartender')

# bartender/models.py
class Bartender(models.Model):
    name = models.CharField(max_length=64)
    owner = models.ForeignKey(User)

# property/models.py
class Rating(models.Model):
    bartender = models.ForeignKey('bartender.Bartender')
    owner = models.ForeignKey(User)

我使用django rest框架,并且想要一个序列化器字段:

# bartender/serializers.py
class BartenderSerializer(serializers.ModelSerializer):
    rating = serializers.IntegerField(source='get_rating', read_only=True)

    class Meta:
        model = Bartender
        fields = []

我的观点是

class BartenderViewset(viewsets.ModelViewSet):
    queryset = Bartender.objects.all()
    serializer_class = BartenderSerializer

如何向我的Bartender模型添加模型方法,以便为正在进行调用的Rating返回User个对象。

我尝试对Bartender课程进行此修改:

# bartender/models.py
class Bartender(models.Model):
    name = models.CharField(max_length=64)
    owner = models.ForeignKey(User)

    def get_rating(self):
        return Rating.objects.get(bartender=self.id, owner=self.request.user)

但是self没有请求。因此,我想知道如何实现它,以便可以通过drf viewsets进行调用。

1 个答案:

答案 0 :(得分:2)

实际上,您可以在不修改模型的情况下执行此操作。只需使用SerializerMethodField评估序列化程序级别的数据:

class BartenderSerializer(serializers.ModelSerializer):
    rating = serializers.SerializerMethodField()

    class Meta:
        model = Bartender
        fields = []

    def get_rating(self, obj):
        return Rating.objects.get(bartender=obj.id, owner=self.context.get('request').user).values('rating')