我有一个模特:
User
是来自django.contrib.auth.models
# 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进行调用。
答案 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')