Я новичок в Django REST, я пытался сделать какую-то запись в БД, используя serilaizer в django rest.Но я получаю некоторые ошибки при использовании метода создания.
Мои модели,
class CoreInformation(models.Model):
site_name = models.CharField(max_length=145, blank=True, null=True)
status = models.CharField(max_length=45, blank=True, null=True)
created_at = models.DateTimeField(blank=True, null=True, auto_now_add=True)
class Meta:
managed = False
db_table = 'core_information'
class CoreDetailInformation(models.Model):
core_info = models.ForeignKey('CoreInformation', models.DO_NOTHING, related_name='core_base_info')
old_sac = models.CharField(max_length=45, blank=True, null=True)
msc = models.CharField(max_length=45, blank=True, null=True)
class Meta:
db_table = 'core_detail_information'
И у меня есть два ModelSerializer, как показано ниже,
class CoreDetailSerializer(serializers.ModelSerializer):
class Meta:
model = CoreDetailInformation
fields = ('id','old_sac', 'msc')
class CustomCoreInfoSerializer(serializers.ModelSerializer):
core_base_info = CoreDetailSerializer(many=True)
class Meta:
model = CoreInformation
# fields = '__all__'
fields = ('id', 'site_name', 'status', 'created_at', 'core_base_info')
@transaction.atomic
def create(self, validated_data):
try:
with transaction.atomic():
base_info = CoreInformation.objects.create(site_name=validated_data['site_name'],status=validated_data['status']
for site_detail in validated_data['core_base_info']:
CoreDetailInformation.objects.get_or_create(msc=site_detail['msc'],old_sac=site_detail['old_sac'],core_info=base_info)
except CoreInformation.DoesNotExist as e:
raise e
except CoreDetailInformation.DoesNotExist as e:
raise e
и мойviews.py is,
class CoreInformation(generics.ListCreateAPIView):
queryset = models.CoreInformation.objects.all()
serializer_class = CustomCoreInfoSerializer
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
instance = self.perform_create(serializer)
serializer = self.get_serializer(instance=instance)
return Response(serializer.data, status=status.HTTP_201_CREATED)
def perform_create(self, serializer):
return serializer.create(validated_data=serializer.validated_data)
Чтобы создать CoreInformation
, мой ввод будет таким, как показано ниже,
{
"site_name": "xxxxxxxxxx",
"status": "create",
"core_base_info": [{
"old_sac": '1',
"msc": "abc1,abc2"
},
{
"old_sac": '2',
"msc": "abc3,abc4"
}]
}
Но когда я компилирую, он возвращает мне ошибку ниже,
AssertionError at /api/core/
The `.create()` method does not support writable nested fields by default.
Write an explicit `.create()` method for serializer `src.core.serializers.CustomCoreInfoSerializer`, or set `read_only=True` on nested serializer fields.
Я нашел это , но мне это не помогло.
Любая помощь будет принята с благодарностью.Благодарю.