Я хочу опубликовать запрос на создание множества экземпляров для связи нового экземпляра, но когда один из многих экземпляров формат не подходит, я хочу сообщить клиенту, что происходит. Но никаких сообщений об ошибке не было. Я хочу знать, почему.
serializer.py
class MenuInfoSerializer(serializers.ModelSerializer):
class Meta:
model = MenuInfo
exclude = ['id']
class MenuSerializer(serializers.ModelSerializer):
info_list = MenuInfoSerializer(source='infos', many=True, read_only=True)
class Meta:
model = Menu
fields = '__all__'
models.py
class MenuInfo(models.Model):
bid_code = models.ForeignKey(Menu, related_name='infos', on_delete=models.CASCADE)
service_type = models.CharField(max_length=32, default='', help_text='服务器型号')
vendor = models.CharField(max_length=32, blank=False, help_text='厂商')
power_dissipation = models.CharField(max_length=32, default='', help_text='满负荷功耗')
weight = models.CharField(max_length=32, default='', help_text='重量')
frame_size = models.CharField(max_length=32, default='', help_text='机框尺寸')
price_3year = models.CharField(max_length=32, default='', help_text='三年含税单价')
price_4year = models.CharField(max_length=32, default='', help_text='四年含税单价')
price_5year = models.CharField(max_length=32, default='', help_text='五年含税单价')
tax_rate = models.CharField(max_length=32, default='', help_text='含税率')
class Meta:
db_table = 'tbl_menu_info'
class Menu(models.Model):
bid_code = models.CharField(primary_key=True, max_length=64, unique=True)
menu_code = models.CharField(max_length=64, unique=True)
config_type = models.CharField(max_length=64, unique=True)
one_bid = models.CharField(choices=SUPPLIER, max_length=32, db_column='bid1', blank=True, default='')
two_bid = models.CharField(choices=SUPPLIER, max_length=32, db_column='bid2', blank=True, default='')
one_two_ratio = models.FloatField(db_column='12_ratio', blank=True, default=-1)
price = models.FloatField(blank=True, default=-1)
class Meta:
db_table = 'tbl_menu'
views.py
class MenuList(generics.ListAPIView):
queryset = Menu.objects.all()
serializer_class = MenuSerializer
name = 'menu-list'
ordering_fields = ('-pk',)
def post(self, request, *args, **kwargs):
with transaction.atomic():
save_id = transaction.savepoint()
menu = request.data
serializer = self.serializer_class(data=menu)
if not serializer.is_valid():
transaction.savepoint_rollback(save_id)
return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST)
serializer.save()
info_list = request.data.get('info_list')
info_serializer = MenuInfoSerializer(data=info_list, many=True)
if not info_serializer.is_valid():
transaction.savepoint_rollback(save_id)
# if not valid, this will raise error
return Response(data=info_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
info_serializer.save()
return Response(data=serializer.data, status=status.HTTP_201_CREATED)
Это мой запрос json, когда поля vendor и bid_code равны "" или null. Ответ вызовет ошибку AttributeError: 'str' object has no attribute 'pk'
Когда я перейду на return Response(data=info_serializer.errors[0], status=status.HTTP_400_BAD_REQUEST)
, все в порядке. Я хочу знать почему?
{
"bid_code": "qqq3",
"info_list": [
{
"bid_code": "",
"service_type": "xxx",
"vendor": "",
"power_dissipation": "xxx",
"weight": "xxx",
"frame_size": "xxx",
"price_3year": "1",
"price_4year": "2",
"price_5year": "3",
"tax_rate": "1.5"
}
],
"menu_code": "qqq3",
"config_type": "qqqsdfsd",
"one_bid": "dell",
"two_bid": "inspur",
"one_two_ratio": 0.5,
"price": 100000,
"purchase_quantity": "xxx",
"application_scene": "xxx",
...