I have two models, DocumentData & RecurringInvoice, which have a one to one relationship with each other. When I create an entry in the RecurringInvoice table, I want to pass in the DocumentData instance, instead of the id. But I get an error saying:
{'document_data': [ErrorDetail(string='Incorrect type. Expected pk value, received DocumentData.', code='incorrect_type')]}
It works if I pass the id of the instance though. From what I know, we can pass in either the instance or the id to link the entries. So why does it fail when I pass the instance?
Relevant controller code:
try:
# get the document data instance
doc_data = DocumentData.objects.get(id=docDataID)
except DocumentData.DoesNotExist:
return Response({
"message": "Document data does not exist"
}, status=status.HTTP_400_BAD_REQUEST)
invoice_serializer = RecurringInvoiceSerializer(
data={
"document_data": doc_data,
"send_date": request.data["send_date"],
"recipients": request.data["recipients"],
"invoice_name": request.data["invoice_name"]
}
)
if not invoice_serializer.is_valid():
print(invoice_serializer.errors, invoice_serializer._errors)
return Response({"message": "Failed to save invoice data"}, status=status.HTTP_400_BAD_REQUEST)
invoice_serializer.save()
RecurringInvoice model:
class RecurringInvoice(models.Model):
document_data = models.OneToOneField(
DocumentData, on_delete=models.CASCADE, null=True, blank=True)
send_date = models.IntegerField(
default=1,
validators=[MinValueValidator(1), MaxValueValidator(28)]
)
invoice_name = models.CharField(max_length=255)
recipients = ArrayField(models.CharField(max_length=100))
is_paused = models.BooleanField(default=False)
stop_date = models.DateField(blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self) -> str:
return f"ID: {self.id}, Name: {self.invoice_name}, Active Till: {self.stop_date}"
class Meta:
verbose_name = "Recurring Invoice"
verbose_name_plural = "Recurring Invoices"
DocumentData model:
class DocumentData(models.Model):
invoices_sent_count = models.IntegerField(default=0)
service_category = models.CharField(max_length=255, blank=True, null=True)
from_company_name = models.CharField(max_length=255)
from_company_number = models.CharField(
max_length=255, blank=True, null=True
)
from_company_address = models.CharField(
max_length=255, blank=True, null=True
)