I would like to know how to go about posting multiple JSON objects to the server using django-restframework. My datatable model is given below.
class module(models.Model):
uploaded_by=models.ForeignKey(ChangeLog,on_delete=models.CASCADE,null=True)
panel_manufacturer= models.CharField(max_length=100,null=True, blank = True)
panel_model= models.CharField(max_length=100,null=True, blank = True)
panel_serial_number = models.CharField(max_length=100)
label_pmpp=models.FloatField(null=True, blank = True)
label_lower_tolerance=models.FloatField(null=True, blank = True)
label_upper_tolerance=models.FloatField(null=True, blank = True)
label_isc=models.FloatField(null=True, blank = True)
label_voc=models.FloatField(null=True, blank = True)
label_maximum_system_voltage=models.FloatField(null=True, blank = True)
additional_panel_information = JSONField(null=True, blank = True)
def __str__(self):
return self.panel_serial_number
And the corresponding serializer is as such
class module_Serializer(serializers.HyperlinkedModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name="pvlabs_testdata:module-detail")
uploaded_by = ChangeLog_Serializer(required=False)
class Meta:
model = module
fields = '__all__'
validators = [module_validator]
def create(self, validated_data):
uploaded_by_data = {"uploaded_by":self.context['request'].user, "upload_timestamp":datetime.now()}
uploaded_by_instance = ChangeLog.objects.create(**uploaded_by_data)
module_instance=module.objects.create(uploaded_by=uploaded_by_instance, **validated_data)
return module_instance
When I go about posting a JSON like below
{
"panel_manufacturer": "XYZ",
"panel_model": null,
"panel_serial_number": "EFG",
"label_pmpp": null,
"label_lower_tolerance": null,
"label_upper_tolerance": null,
"label_isc": null,
"label_voc": null,
"label_maximum_system_voltage": null,
"additional_panel_information": null
},
{
"panel_manufacturer": "XYZ",
"panel_model": null,
"panel_serial_number": "ABC",
"label_pmpp": null,
"label_lower_tolerance": null,
"label_upper_tolerance": null,
"label_isc": null,
"label_voc": null,
"label_maximum_system_voltage": null,
"additional_panel_information": null
},
{
"panel_manufacturer": "XYZ",
"panel_model": null,
"panel_serial_number": "ABC",
"label_pmpp": null,
"label_lower_tolerance": null,
"label_upper_tolerance": null,
"label_isc": null,
"label_voc": null,
"label_maximum_system_voltage": null,
"additional_panel_information": null
}
I always get an error that says 'Expected dict, got list'.
I managed to create a solution for this using list serializer. So in my views file, it is coded as below
class module_ViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows groups to be viewed or edited.
"""
queryset = module.objects.all()
serializer_class = module_Serializer
permission_classes = [permissions.IsAuthenticated | HasAPIKey]
def get_serializer(self, *args, **kwargs):
if isinstance(kwargs.get("data", {}), list):
kwargs["many"] = True
temp= kwargs.get("data")
for i in range(len(kwargs.get("data"))):
for key, value in temp[i].items():
if " " in key or key.islower()==0:
n_key=str(key).replace(" ", "_").title().lower()
kwargs.get("data")[i][n_key] = kwargs.get("data")[i].pop(key)
return super(module_ViewSet, self).get_serializer(*args, **kwargs)
And for my serializer I have coded as below
from rest_framework import serializers
from django_restql.mixins import DynamicFieldsMixin
class BulkModuleSerializer(DynamicFieldsMixin, serializers.ListSerializer):
def create(self, validated_data):
result=[]
for validated_datas in validated_data:
uploaded_by_data = {"uploaded_by":self.context['request'].user, "upload_timestamp":datetime.now()}
uploaded_by_instance = ChangeLog.objects.create(**uploaded_by_data)
module_instance=module.objects.create(uploaded_by=uploaded_by_instance, **validated_datas)
result.append(module_instance)
return result
class module_Serializer(DynamicFieldsMixin, serializers.HyperlinkedModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name="pvlabs_testdata:module-detail")
uploaded_by = ChangeLog_Serializer(required=False)
class Meta:
model = module
fields = '__all__'
validators = [module_validator]
list_serializer_class = BulkModuleSerializer
def create(self, validated_data):
uploaded_by_data = {"uploaded_by":self.context['request'].user, "upload_timestamp":datetime.now()}
uploaded_by_instance = ChangeLog.objects.create(**uploaded_by_data)
module_instance=module.objects.create(uploaded_by=uploaded_by_instance, **validated_data)
return module_instance
That seems to have worked for me.
You have put your JSON data inside square brackets. Example:
[
{
"panel_manufacturer": "XYZ",
"panel_model": null,
"panel_serial_number": "ABC",
"label_pmpp": null,
"label_lower_tolerance": null,
"label_upper_tolerance": null,
"label_isc": null,
"label_voc": null,
"label_maximum_system_voltage": null,
"additional_panel_information": null
},
{
"panel_manufacturer": "XYZ",
"panel_model": null,
"panel_serial_number": "ABC",
"label_pmpp": null,
"label_lower_tolerance": null,
"label_upper_tolerance": null,
"label_isc": null,
"label_voc": null,
"label_maximum_system_voltage": null,
"additional_panel_information": null
}
]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.