I want to change my url of document so that in response instead of returning with the name of the document, it should return the id of the document. so, /nononoo.txt becomes like this /2 ( id of the document)
This is my response that i am getting,
"id": 2,
"document": "http://127.0.0.1:8000/images/nononno.txt",
"filesize": "13 bytes",
"filename": "nononno.txt",
"mimetype": "text/plain",
"created_at": "2022-09-21"
I want to change this /nononoo.txt to the id of the document so that it becomes like this
"document": "http://127.0.0.1:8000/images/2(id of the current document uploaded)"
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)])
filename=models.CharField(max_length=100, blank=True)
filesize=models.IntegerField(default=0)
mimetype=models.CharField(max_length=100, blank=True)
created_at=models.DateField(auto_now_add=True)
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]
self.filesize=self.document.size
super().save(force_insert, force_update, *args, **kwargs)
class Meta:
verbose_name_plural="Documents"
ordering=["document"]
def __str__(self):
return f'{self.document}'
@property
def sizeoffile(self):
x = self.document.size
y = 512000
if x < y and x < 1000 :
value=round(x, 0)
ext = ' bytes'
elif x < y and x >= 1000 and x < 1000*1000:
value = round(x / 1000)
ext = ' KB'
elif x < y * 1000 and x >= 1000*1000 and x < 1000*1000*1000 :
value = round(x / (1000 * 1000), 2)
ext = ' MB'
elif x >= 1000*1000*1000:
value = round(x / (1000 * 1000 * 1000), 2)
ext = ' GB'
return str(value) + ext
serializers.py
class DocumentSerializer(serializers.ModelSerializer):
filesize=serializers.ReadOnlyField(source='sizeoffile')
class Meta:
model=DocumentModel
fields = ['id', 'document', 'filesize', 'filename', 'mimetype', 'created_at' ]
Please guide me how can i achieve this?