Reputation: 67
I have a model called 'Candidate', which has the fields Experience,New Experience,Date_posted.
I'm using CreateView form to store the values in the database. When I enter experience and date_posted(set to timezone.now) for the first time, the 'new experience' value should also be set to 'experience' value by default. Now this 'new experience' value should get incremented after every month.
For example, experience=2.4 ( 2 years 4 months ), new experience =2.4( set automatically )
So, If I open my template(website page) 1 month from now, the 'experience' and 'date_posted' values must be same, but 'new experience' = 2.5 ( 2 years, 5 months )
class CandidateCreateView(LoginRequiredMixin, CreateView):
model = Candidate
fields = ['candidate_name', 'experience', 'email', 'new_experience']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
Also, I want to use the format, 2.12 ( for 2 years 12 months )and 3.1 ( for 2 years 13 months ). How do I achieve this?
Upvotes: 0
Views: 212
Reputation: 926
Maybe you can set your new_experience
as a computed property, rather than a normal field?
from datetime import datetime
class Candidate:
# ...
experience = models.DateField()
@property
def new_experience(self):
now = datetime.now().date()
delta = now - self.date_posted
return (self.experience + delta)
After your clarification in the comments, my suggestion would be to split the experience
field into years and months:
class Candidate:
# ...
experience_years = models.IntegerField()
experience_months = models.IntegerField()
@property
def new_experience(self):
base_experience = datetime.datetime(year=self.expreience_years, month=self.experience_months, day=1)
delta = datetime.datetime.now() - self.date_posted
new_experience = base_experience + delta
# now you can access new_experience.year, new_experience.month
return new_experience
Another option be can be to return a tuple
from new_experience (years,months)
, as computed above
Warning: Quick and dirty but not tested
Upvotes: 1