How to correctly write viewset and serializer for saving file in mongo and add mongo_id to Postgre table?

Viewed 36

My model looks like this:

class Document(models.Model):
  id: int = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)  # type: ignore
  order_id: str = models.CharField(max_length=255)  # type: ignore
  publicated_at: datetime = models.DateTimeField(null=True)  # type: ignore
  expired_at: datetime = models.DateTimeField(null=True)  # type: ignore
  created_at: datetime = models.DateTimeField(auto_now_add=True)  # type: ignore
  updated_at: datetime = models.DateTimeField(auto_now=True)  # type: ignore
  department: Department = models.ForeignKey(Department, on_delete=models.DO_NOTHING, null=True, blank=True)  # type: ignore
  file_name: str = models.CharField(max_length=255)  # type: ignore
  owner: CustomUser = models.ForeignKey(CustomUser, on_delete=models.DO_NOTHING, null=True, related_name='owned_documents')  # type: ignore
  loaded_by: CustomUser = models.ForeignKey(CustomUser, on_delete=models.DO_NOTHING, null=True, blank=True, related_name='loaded_documents')  # type: ignore
  
  file_id: str = models.CharField(max_length=255, null=True, blank=False)  # type: ignore
  metrics: Metric = models.ManyToManyField(Metric, through="DocumentsMetrics", related_name="documents")  # type: ignore
  document_status: DocumentStatus = models.ForeignKey(DocumentStatus, on_delete=models.SET_NULL, null=True)  # type: ignore
  issue: str = models.TextField(null=True, blank=True)  # type: ignore
  suggestion: str = models.TextField(null=True, blank=True)  # type: ignore

  class Meta:
    app_label = 'library'

  mongo_file_key = 'file_id'

  def upsert_document(self, buffer: IStream) -> None:
    file_ms.update_from_bytes(self, self.mongo_file_key, buffer)

  def get_document_bytes(self) -> IStream | None:
    return file_ms.get_bytes(self, self.mongo_file_key)

  def save_document(self, path: str) -> None:
    with open(path, 'wb') as f:

I am storing a "Document" object in PostgreSQL. In the file_id field, I insert the id from mongoDB. My model has method

upsert_document

to save file to mongo which returns mongo_id.

env:

  • django version 3.9
  • python version 3.10
  • drf version 3.13

How to write viewset and serializer to validate and process a request?

0 Answers
Related