Hi,
I’m a bit newbie with django.
I want to do a POST in a endpoint and validate if the foreign key exists or not.
My models:
# TABELA DOS FORNECEDORES
class Fornecedor(models.Model):
nome = models.CharField(max_length=100, null=False, blank=False)
endereco = models.CharField(max_length=100, null=False, blank=False)
codigo_postal = models.CharField(max_length=8, null=False, blank=False)
cidade = models.CharField(max_length=50, null=False, blank=False)
nif = models.IntegerField(
null=False,
blank=False,
unique=True,
validators=[
RegexValidator(r"[1-9]\d*"),
MinLengthValidator(9),
MaxLengthValidator(9),
MaxValueValidator(999999999),
MinValueValidator(1),
],
)
email = models.EmailField(max_length=50, null=False, blank=False)
data_registo = models.DateTimeField(auto_now_add=True)
data_ultimo_login = models.DateTimeField(auto_now=True)
ativo = models.BooleanField(default=True, null=False, blank=False)
def __str__(self):
return self.nome
# TABELA DAS MARCAS
class Marca(models.Model):
nome = models.CharField(max_length=55, null=False, blank=False)
fornecedor = models.ForeignKey(
Fornecedor, on_delete=models.CASCADE, null=False, blank=False
)
def __str__(self):
return self.nome
My serializers
class FornecedorSerializer(serializers.ModelSerializer):
class Meta:
model = Fornecedor
fields = "__all__"
class MarcaSerializer(serializers.ModelSerializer):
class Meta:
model = Marca
fields = "__all__"
My views
class FornecedorPOST(APIView):
@swagger_auto_schema(
operation_summary="Criar um Fornecedor",
operation_description="Criar um novo Fornecedor",
request_body=FornecedorSerializer,
responses={
status.HTTP_201_CREATED: response_201(FornecedorSerializer),
status.HTTP_400_BAD_REQUEST: response_400(FornecedorSerializer),
},
)
def post(self, request, format=None):
fornecedor = FornecedorSerializer(data=request.data)
if fornecedor.is_valid():
fornecedor.save()
return Response(fornecedor.data, status=status.HTTP_201_CREATED)
return Response(fornecedor.errors, status=status.HTTP_400_BAD_REQUEST)
class MarcaPOST(APIView):
@swagger_auto_schema(
operation_summary="Criar uma marca",
operation_description="Criar uma nova marca",
request_body=MarcaSerializer,
responses={
status.HTTP_201_CREATED: response_201(MarcaSerializer),
status.HTTP_400_BAD_REQUEST: response_400(MarcaSerializer),
},
)
def post(self, request, format=None):
marca = MarcaSerializer(data=request.data)
if marca.is_valid():
marca.save()
return Response(marca.data, status=status.HTTP_201_CREATED)
return Response(marca.errors, status=status.HTTP_400_BAD_REQUEST)
My urls
urlpatterns = [
# URLS API ENDPOINTS
path("api/fornecedor/", views.FornecedorPOST.as_view(), name="add_single_supplier_api"),
path("api/marca/", views.MarcaPOST.as_view(), name="add_single_brand_api"),
path("api/docs", schema_view.with_ui("swagger", cache_timeout=0)),
]
Basically I want to add new Marca and use nif field from Fornecedor instead of Fornecedor pk and ofc validate if exists.
Thanks in advance.