我有两个模型
我添加了一个掩码到一个模型,其中每个字母对应的值A,到第二个我将添加一个序列号,我需要这个字段来检查这个匹配值掩码
models.py
class EquipmentType(models.Model):
name = models.CharField(max_length=255)
mask = models.CharField(max_length=100)
class Equipment(models.Model):
type = models.ForeignKey('EquipmentType', on_delete=models.CASCADE)
sn = models.CharField(max_length=255, unique=True)
note = models.CharField(max_length=255)
def clean(self):
mask = self.type
regex = ''
for char in mask:
if char == 'N':
regex += 'd'
elif char == 'A':
regex += '[A-Z]'
elif char == 'a':
regex += '[a-z]'
elif char == 'X':
regex += '[A-Z0-9]'
elif char == 'Z':
regex += '[-_@]'
if not re.match(regex, self.sn):
raise ValidationError({'serial_number': 'Invalid serial number'})
class Meta:
unique_together = ('sn', 'type')
serializers.py
class EquipmentSerializer(serializers.ModelSerializer):
class Meta:
model = Equipment
fields = '__all__'
def validate_serial_number(self, value):
mask = self.instance.type.mask
regex = ''
for char in mask:
if char == 'N':
regex += 'd'
elif char == 'A':
regex += '[A-Z]'
elif char == 'a':
regex += '[a-z]'
elif char == 'X':
regex += '[A-Z0-9]'
elif char == 'Z':
regex += '[-_@]'
for num in value:
if not re.match(regex, num):
raise serializers.ValidationError('Invalid serial number')
return value
class EquipmentTypeSerializer(serializers.ModelSerializer):
class Meta:
model = EquipmentType
fields = '__all__'
views.py
class EquipmenAPIListPagination(PageNumberPagination):
page_size = 3
page_size_query_param = 'page_size'
max_page_size = 100
class EquipmentAPIList(generics.ListCreateAPIView):
queryset = Equipment.objects.all()
serializer_class = EquipmentSerializer
permission_classes = (IsAuthenticatedOrReadOnly, )
pagination_class = EquipmenAPIListPagination
filter_backends = (filters.DjangoFilterBackend,)
filterset_class = EquipmentFilter
def post(self, request, format=None):
data = request.data
many = isinstance(data, list)
serializer = EquipmentSerializer(data=request.data, many=many)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class EquipmentAPIView(APIView):
def get(self, request, *args, **kwargs):
pk = kwargs.get("pk", None)
if not pk:
w = Equipment.objects.all()
return Response({'posts': EquipmentSerializer(w, many=True).data})
mymodel = get_object_or_404(Equipment, pk=pk)
serializer = EquipmentSerializer(mymodel)
return Response(serializer.data)
def put(self, request, *args, **kwargs):
pk = kwargs.get("pk", None)
if not pk:
return Response({"error": "Method PUT not allowed"})
try:
instance = Equipment.objects.get(pk=pk)
except:
return Response({"error": "Object does not exists"})
serializer = EquipmentSerializer(data=request.data, instance=instance)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response({"post": serializer.data})
def delete(self, request, *args, **kwargs):
pk = kwargs.get("pk", None)
if not pk:
return Response({"error": "Method DELETE not allowed"})
return Response({"post": "delete post " + str(pk)})
class EquipmentTypeAPIList(generics.ListCreateAPIView):
queryset = EquipmentType.objects.all()
serializer_class = EquipmentTypeSerializer
permission_classes = (IsAuthenticatedOrReadOnly, )
pagination_class = EquipmenAPIListPagination
filter_backends = (filters.DjangoFilterBackend,)
filterset_class = EquipmentTypeFilter
def post(self, request, format=None):
data = request.data
many = isinstance(data, list)
serializer = EquipmentTypeSerializer(data=data, many=many)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class EquipmentTypeAPIView(APIView):
def get(self, request, *args, **kwargs):
pk = kwargs.get("pk", None)
if not pk:
w = EquipmentType.objects.all()
return Response({'posts': EquipmentTypeSerializer(w, many=True).data})
mymodel = get_object_or_404(Equipment, pk=pk)
serializer = EquipmentTypeSerializer(mymodel)
return Response(serializer.data)
我这样做了,但验证不起作用。所有的数字一般都是加起来的,我该怎么修?
1条答案
按热度按时间lhcgjxsq1#
您的字段在模型上称为
sn
,您需要将序列化器上的验证方法更改为validate_sn
而不是validate_serial_number
,以便DRF正确地选择并应用它。