How to add custom row level processing of a column in Django Model that is used by Viewsets

Multi tool use


How to add custom row level processing of a column in Django Model that is used by Viewsets
Here is my Model for eg. :
class Lics(models.Model):
files_id = models.IntegerField(blank=True, null=True)
seqno = models.IntegerField(blank=True, null=True)
expire = models.TextField(blank=True)
the field 'expire' comes with a date. I have a function that does delta from 'now' when the api is called. How and where do I add an extra field in the ViewSet when calling Lics.objects.all() that has is added as a 4th field which shows 'days' = 4 for eg. if license is expiring 4 days from now.
Expected output : [{files_id:1, seqno:2, expire:'4-jan-2019', 'days':4 }]
[{files_id:1, seqno:2, expire:'4-jan-2019', 'days':4 }]
2 Answers
2
I would probably add it as a SerializerMethodField
so that it's calculated upon request. In fact, this is very similar to the example in the docs. You want something like the following (NOTE: I have not tested this, it is just a slight modification of the documented example):
SerializerMethodField
from django.utils.timezone import now
from rest_framework import serializers
class LicSerializer(serializers.ModelSerializer):
days = serializers.SerializerMethodField()
class Meta:
model = Lic
def get_days(self, obj):
cur_time = now()
if cur_time > obj.expire:
return 0
return (obj.expire - cur_time).days
@RishiG has a good solution. As an alternative, you could also make a model property.
class Lics(models.Model):
files_id = models.IntegerField(blank=True, null=True)
seqno = models.IntegerField(blank=True, null=True)
expire = models.TextField(blank=True)
@property
def days(self):
// calculation code goes here
Then, you just include "days" in the "fields" argument of your serializer.
class LicSerializer(serializers.ModelSerializer):
class Meta:
model = Lic
fields = ('files_id', 'seqno', 'expire', 'days')
I generally decide on my approach based on WHERE I want to be able to access this data. For example, if I might want to operate directly on the days
property of a model instance I put it in the model. If I only care about bubbling this data up in a view, I put it in the serializer.
days
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.