Home > Software engineering >  How to send the data from @property field to database tables in Django
How to send the data from @property field to database tables in Django

Time:08-24

I have a DocumentModel containing some fields including document which is a filefield. I have used @property decorator to get the name, size and mime type of a file which gets uploaded.

The issue that currently i am facing is that @property fields are being shown on frontend in serializers, but its not being show in database tables.

In database tables only id, document, and created_at is being shown but not filename, filesize, and mimetype

Kindly if someone can guide how can i send this @property data to database tables?

Models.py

class DocumentModel(models.Model):
    id=models.AutoField(primary_key=True, auto_created=True, verbose_name="DOCUMENT_ID")
    document=models.FileField(max_length=350 ,validators=  [FileExtensionValidator(extensions)])
    created_at=models.DateTimeField(auto_now_add=True)
    

    class Meta:
        verbose_name_plural="Documents"
        ordering=["document"]

    def __str__(self):
        return f'{self.document}'
    @property
    def filename(self):
        return self.document.name

   

    @property
    def mimetype(self):
        return mimetypes.guess_type(self.document.url)[0]

serializers.py

class DocumentSerializer(serializers.ModelSerializer):

    
            
        

    class Meta:
        model=DocumentModel
        fields = ['id', 'document', 'filesize', 'filename', 'mimetype', 'created_at']

CodePudding user response:

You can simply create fields in your model instead of properties. These will be mapped to the database. Not sure that is a good idea though. You will need to be very careful to ensure data integrity, when changing files. If you are absolutely sure that is what you want/need, you can e.g. override the save method to automatically generate the filename and mimetype field values before saving to the database. Beware thought that the save method is NOT called when you call .objects.update for example.

Something like this would be possible:

class DocumentModel(models.Model):
    id = models.AutoField(primary_key=True, auto_created=True, verbose_name="DOCUMENT_ID")
    document = models.FileField(max_length=350 ,validators=  [FileExtensionValidator(extensions)])
    created_at = models.DateTimeField(auto_now_add=True)
    filename = models.CharField(...)
    mimetype = models.CharField(...)

    def save(self, force_insert=False, force_update=False, *args, **kwargs):
        self.filename = self.document.name
        self.mimetype = mimetypes.guess_type(self.document.url)[0]
        super().save(force_insert, force_update, *args, **kwargs)
  • Related