Django Rest FrameworkでREST APIを作っているのですが、CommandSerializer内でModelViewSetのアクション(POST, PATCH)に応じてextra_kwargsを動的に変更する方法がわかりません。
どうすればできるかおしえてください!
python
1#こんな感じでやりたい! 2 3#post 4if self.action == 'create': 5 extra_kwargs = { 6 'response': {'required': False} 7 } 8#patch 9elif self.action == 'partial_update': 10 extra_kwargs = { 11 'response': {'required': True} 12 }
python
1#シリアライザ 2class CommandSerializer(serializers.ModelSerializer): 3 4 upfile = UpFileSerializer(read_only=True) 5 downfile = DownFileSerializer(read_only=True) 6 7 class Meta: 8 model = Command 9 fields = '__all__' 10 extra_kwargs = { 11 'response': {'required': False} 12 } 13 14 15 def create(self, validated_data): 16 c = Command( 17 sender=validated_data['sender'], 18 cmd=validated_data['cmd'], 19 recipient=validated_data['recipient'] 20 ) 21 c.finished('cmd') 22 return c 23 24 def update(self, instance, validated_data): 25 instance.response = validated_data.get('response', instance.response) 26 instance.finished('resp') 27 return instance
python
1#モデル 2class Command(models.Model): 3 sender = models.IntegerField() 4 cmd = models.TextField() 5 recipient = models.TextField() 6 response = models.TextField() 7 upfile = models.OneToOneField(UpFile, default=None, null=True, blank=True, unique=True, related_name='command', on_delete=models.CASCADE) 8 downfile = models.OneToOneField(DownFile, default=None, null=True, blank=True, unique=True, related_name='command', on_delete=models.CASCADE) 9 cmd_finished = models.DateTimeField(null=True, blank=True) 10 resp_finished = models.DateTimeField(null=True, blank=True) 11 12 def finished(self, op): 13 if op == 'cmd': 14 self.cmd_finished = timezone.now() 15 elif op == 'resp': 16 self.resp_finished = timezone.now() 17 self.save() 18 19 def connect_upfile(self, qs): 20 self.upfile = qs 21 self.save() 22 23 def connect_downfile(self, qs): 24 self.downfile = qs 25 self.save()
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。