'Override create method
New to drf.I have json input data like below:
{
"name":"df",
"email":"[email protected]",
"age":"21",
"gender":"Male",
"phone":"234",
"total_price":86,
"advance":0,
"due":86,
"selected":[{"id":8,"name":"sdf"},{"id":9,"name":"dg"}]
}
Below is my views.py.I want to override create method for the json input data.But no idea how to do it.
class PatientEntry(generics.CreateAPIView):
queryset = Test.objects.all()
serializer_class = PatientSerializer
def create(self, request, *args, **kwargs):
many = isinstance(request.data, list)
serializer = self.get_serializer(data=request.data,many=True)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, headers=headers)
serializers.py:
class PatientSerializer(serializers.ModelSerializer):
class Meta:
model = Patient
fields = '__all__'
models.py:
class Patient(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField(max_length = 254)
age = models.IntegerField()
gender = models.CharField(max_length=100)
phone = models.IntegerField()
test_id = models.IntegerField()
test_name = models.CharField(max_length=100)
total = models.DecimalField(max_digits=6, decimal_places=0)
advance = models.DecimalField(max_digits=6, decimal_places=2)
due = models.DecimalField(max_digits=6, decimal_places=2)
role = models.CharField(max_length=100,default='Patient')
From selected key, "selected":[{"id":8,"name":"sdf"},{"id":9,"name":"dg"}]
id should add in test_id field and name should add in test_name field
Solution 1:[1]
ModelSerializer will guess required field through your models. Because your models define required properties, the serializer field also have them as required.
To override this, you need to either loose requirements on your models, either tell the serializer to overide the 'required' = True:
class Meta:
model = YourModel
fields = '__all__'
extra_kwargs = {'mymissingfield': {'required': False}}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sami Tahri |
