django,在保存到数据库之前更改模型中的字段值

时间:2020-10-07 05:28:06

标签: python django django-rest-framework

类PlayerList(models.Model):

name = models.CharField(max_length=300)
position = models.CharField(max_length=200)
h_code = models.ForeignKey(HList, related_name="h_code", on_delete=models.CASCADE)
d_code = models.CharField(primary_key=True, max_length = 200, editable=False)

Serializers.py

class PlayerSerializer(serializers.ModelSerializer):    
    class Meta:
        fields = ["name", "position", "h_code", "d_code"]
        model = PlayerList

view.py

class PostPlayer(generics.ListCreateAPIView):
    queryset = PlayerList.objects.all().order_by('-d_code')
    serializer_class = PlayerListSerializer

    def get(self, request, *args, **kwargs):
        d_code = request.data.get('h_code') + 'test'
        print(d_code)

print(d_code):

h000001test

通过api输入值时,我想实现将输入的值更改为view.py中的另一个值并保存在数据库中。

我想将def处理的d_code保存到数据库中。

我不知道该怎么办。你能告诉我吗?

没有答案,所以我会再次发布。

1 个答案:

答案 0 :(得分:1)

您可以按照docs中的说明重写视图perform_create()方法(您可能需要在 Save and delete hooks 部分中进行一些滚动,< / p>

class PostPlayer(generics.ListCreateAPIView):
    queryset = PlayerList.objects.all().order_by('-d_code')
    serializer_class = PlayerListSerializer

    def get(self, request, *args, **kwargs):
        d_code = request.data.get('h_code') + 'test'
        print(d_code)
    ...
    ...
    def perform_create(self, serializer):
        d_code = request.data.get('h_code') + 'test'
        #do something with d_code
        new_code = d_code + 'someSampleValue'
        serializer.save(d_code=new_code)