Am aiming for the value 'grade' to be incremented by 1 on 25th every month. The below function doesn't seem to be working. Where could I be going wrong?
Attached is the model and function.
class Student(models.Model):
student_name = models.CharField(max_length=100, null=True)
extra_role = models.CharField(max_length=100, default='None', null=True)
gender = models.CharField(max_length=20, choices = gender, default = "female")
dob = models.DateField(null=True, blank=True)
grade = models.IntegerField(choices=grade)
parent_phone = PhoneField(blank=True, help_text='Contact phone number')
# admNo = models.AutoField()
#property
def age(self):
if(self.dob != None):
age = date.today().year - self.dob.year
return age
#property
def sgrade(self):
if datetime.today().day == 25:
grade = self.grade +1
return grade
Please try this one :
def age(self):
if(self.dob != None):
today = datetime.datetime.today()
return today.year - self.dob.year - ((today.month, today.day) < (self.dob.month, self.dob.day))
def sgrade(self):
if datetime.datetime.now().day == 25:
grade = self.grade +1
return grade
Don't forget to import datetime
Related
I have a model name Employee now i want to add a new fields in this model which will be a foreign key of Department model.I try to solve it the following way but i get error like
django.db.utils.IntegrityError: The row in table 'employee_verification_employee' with primary key 'UP-0319001' has an invalid foreign key: employee_verification_employee.department_id contains a value '03' that does not have a corresponding value in employee_verification_department.id.
class Department(models.Model):
name = models.CharField(max_length=100)
id = models.CharField(primary_key=True,max_length=10)
class Employee(models.Model):
name = models.CharField(max_length=100)
department = models.CharField(max_length=100,choices = Departments)
date_of_joining = models.DateField()
employeed = models.BooleanField(default = True)
email = models.EmailField(max_length = 254)
blood_group = models.CharField(max_length=50)
designation = models.CharField(max_length=100)
image = models.ImageField(upload_to='employee_images',default = "")
number = PhoneField(blank=True, help_text='Enter Contact Number')
emergency_number = PhoneField(blank=True, help_text='Enter Contact Number')
id = models.CharField(primary_key=True, max_length=200)
department_new = models.ForeignKey(Department,on_delete=models.CASCADE,blank=True)
def save(self, *args, **kwargs):
if not self.id:
nth_member = Employee.objects.filter(department = self.department).count()+1
self.id = "UP-" + self.department + self.date_of_joining.strftime("%y")+"{:03d}".format(nth_member)
print(self.id)
super(Employee, self).save(*args, **kwargs)
def __str__(self):
return self.name + "--"+ self.designation``
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/xdRMd.png
As #trigo said, all you need is:
class Department(models.Model):
name = models.CharField(max_length=100)
class Employee(models.Model):
name = models.CharField(max_length=100)
department = models.CharField(max_length=100,choices = Departments)
date_of_joining = models.DateField()
employeed = models.BooleanField(default = True)
email = models.EmailField(max_length = 254)
blood_group = models.CharField(max_length=50)
designation = models.CharField(max_length=100)
image = models.ImageField(upload_to='employee_images',default = "")
number = PhoneField(blank=True, help_text='Enter Contact Number')
emergency_number = PhoneField(blank=True, help_text='Enter Contact Number')
department_new = models.ForeignKey(Department,on_delete=models.CASCADE,blank=True)
And Django will take care of the rest (ids).
I am learning django or a month now. I created a model called "Leave" to mark employees leave. Then I created a model called "Salarie".In this I need to create a field like "Total_Leave" which will show an employees leave count in a month.( In january 2020 how many leave a particular employee took) ( If i mention the "Employee_Name" as "Samantha" in salary model, it need to show samantas' leave in the particular month,year)
I tried to do it like this and tried some coding but nothing worked.
#property
def Total_Leave(self):
return self.
Can anyone explain me how to do that please?
Models.py
class Leave(models.Model):
Leave_ID = models.CharField(max_length=5, primary_key=True,default=" ")
Employee_Name = models.ForeignKey('Employee_Detail',models.DO_NOTHING)
Dept_Name = models.ForeignKey('Department', models.DO_NOTHING)
l = (
("Paid","Paid"),("Non-Paid","Non-Paid")
)
Leave_Type = models.CharField(max_length=10, choices= l, default="Non-Paid")
m = (
("January","January"),("February","February"),("March","March"),("April","April"),("May","May"),("June","June"),("July","July"),("August","August"),("September","September"),("October","October"),("November","November"),("December","december")
)
Month = models.CharField(max_length=10, choices= m)
Year = models.IntegerField(max_length=4)
Start_Date = models.DateField()
End_Date = models.DateField(null=True, blank = True)
Reason = models.CharField(max_length=200)
s = (
("Accepted","Accepted"),("Pending","Pending"),("Canceled","Canceled")
)
Status = models.CharField(max_length=10, choices= s, default="Pending")
def __str__(self):
return str(self.Employee_Name)
class Salarie(models.Model):
Salarie_ID = models.CharField(max_length=5,primary_key=True,default=" ")
Employee_Name = models.ForeignKey('Employee_Detail', models.DO_NOTHING)
Dept_Name = models.ForeignKey('Department', models.DO_NOTHING)
Basic_Salary = models.IntegerField(default=0)
Extra_Hours = models.IntegerField(default=0)
#property
def Extra_Payment(self):
return self.Extra_Hours * 350
Bonus = models.IntegerField(default=0)
#property
def Total_Payment(self):
return self.Extra_Payment + self.Basic_Salary + self.Bonus
m = (
("January","January"),("February","February"),("March","March"),("April","April"),("May","May"),("June","June"),("July","July"),("August","August"),("September","September"),("October","October"),("November","November"),("December","december")
)
Month = models.CharField(max_length=10, choices= m)
Year = models.IntegerField(max_length=4)
Status = models.BooleanField()
Paid_Date = models.DateField(null=True,blank=True)
def __str__(self):
return str(self.Employee_Name)
class Employee_Detail(models.Model):
Employee_ID = models.CharField(primary_key=True, max_length=6)
Employee_Name = models.CharField(unique=True, max_length=30)
Primary_Phone = models.IntegerField(unique=True, max_length=10)
p = (
("Manager","Manager"),("Supervisor","Supervisor"),("Employee","Employee")
)
Position = models.CharField(max_length=15, choices= p, default="Employee")
Address = models.TextField(max_length=500)
Email = models.EmailField(max_length=50, unique=True)
def __str__(self):
return str(self.Employee_Name)
You can do this by using annotate or aggregate
If you want leave count for all the employees then
from django.db.models import Count
employees = Employee_Detail.objects.filter(leave__Status='Accepted').annotate(leave_count=Count('leave'))
you can access this by <employee Obj>.leave_count
If you want leave count for all employee order_by Month then
employees = Employee_Detail.objects.filter(leave__Status='Accepted').order_by('leave__Month').annotate(leave_count=Count('leave')).values('leave_Month','leave_count')
And last you want leave count for a particular employee for a particular month than in your employee model write #property function like this
#property
def get_leave_count(self):
leaves = Employee_Detail.objects.filter(id=self.id,leave__Status='Accepted').aggregate(leave_count=Count('leave'))
return leaves['leave_count']
for month and year wise provide month and year and then
month = 'January' #For example
leaves = Employee_Detail.objects.filter(id=employee_id,leave__Month=month,leave__Status='Accepted').aggregate(leave_count=Count('leave'))
#{'leave_count':3}
year = '2020' #For example
leaves = Employee_Detail.objects.filter(id=employee_id,leave__Year=year,leave__Status='Accepted').aggregate(leave_count=Count('leave'))
#{'leave_count':13}
I tried something like this, maybe of some use.
def total_leave(emp_name,month,year):
leaves = Leave.objects.filter(Emp_name= emp_name,Month=month,Year=year)
Count=0
for leave in leaves:
if leaves.status== "Accepted":
Count +=1
return Count
Like if you only need to get leave count for the year, just use year as a parameter for function.
I am building a helpdesk system and I would like to have a automated ticket designation based on the length of the ID.
Example:
The ID of a ticket is 47 so I would like to have a 5 Integer long designation -> #00047 or if ID 2021 designation should be #02021
my relevant code:
My Model:
class Ticket(models.Model):
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
designation = models.CharField(max_length=255, blank=True, null=True)
I tried do populate the fields with a for loop in my views.py
def Index(request):
ticket = Ticket.objects.all()
for t in ticket:
id = len(str(t.id))
if id == 1:
t.designation = "#" + str("0000") + str(t.id)
elif id == 2:
t.designation = "#" + str("000") + str(t.id)
elif id == 3:
t.designation = "#" + str("00") + str(t.id)
elif id == 4:
t.designation = "#" + str("0") + str(t.id)
else:
t.designation = "#" + str(t.id)
context = {'ticket':ticket}
return render(request, 'ticketsystem/index.html', context)
and the output was correct, but I would like to have the population while creating the object
i tried the following, by adding it to my Ticket model:
class Ticket(models.Model):
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
designation = models.CharField(max_length=255, blank=True, null=True)
def save(self):
id = len(str(id))
if id == 1:
designation = "#" + str("0000") + str(id)
elif id == 2:
designation = "#" + str("000") + str(id)
elif id == 3:
designation = "#" + str("00") + str(id)
elif id == 4:
designation = "#" + str("0") + str(id)
else:
designation = "#" + str(id)
super().save()
but following error comes up:
local variable 'id' referenced before assignment
You need to run the super call before everything else, otherwise, your object won't be in the DB.
class Ticket(models.Model):
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
designation = models.CharField(max_length=255, blank=True, null=True)
def save(self):
if not self.pk:
super().save()
str_id = str(self.pk)
if str_id == 1:
self.designation = "#0000{}".format(str_id)
elif str_id == 2:
self.designation = "#000{}".format(str_id)
elif str_id == 3:
self.designation = "#00{}".format(str_id)
elif str_id == 4:
self.designation = "#0{}".format(str_id)
else:
self.designation = "#{}".format(str_id)
return self.save()
You've not overwritten the id field so it is going to be an integer and you want to let Django handle the autoincrement etc.
You would be better off (in my opinion) simply adding a new field which takes the id and converts it to a string
class Ticket(models.Model):
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
#property
def ticketkennung(self):
this_id = str(self.id)
if len(this_id) = 1 : str_id = '0000' + this_id
etc ...
return this_id
OR
class Ticket(models.Model):
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
designation = models.CharField(max_length=255, blank=True, null=True)
def save(self):
this_id = len(str(self.id))
if id == 1: self.designation = "#" + str("0000") + str(id)
etc
super().save(*args, **kwargs)
this is my code
views.py
def guardar(request):
if request.method == "POST":
idpersona = int(request.POST.get('id'))
persona = personal.objects.get(id=idpersona)
idep = int(request.POST.get('dependencia'))
dep = dependencia.objects.get(id=idep)
idcon = int(request.POST.get('concepto'))
con = concepto.objects.get(id=idcon)
fecha = request.POST.get('fecha')
print(fecha)
db_registro = lista_registro(
personal_id=persona,
fecha_registro=fecha,
dependencia_id=dep,
concepto_id=con,
descripcion=request.POST.get('descripcion'),
monto=request.POST.get('monto'),
)
db_registro.save()
return render(request, 'registro/exito.html')
Models.py
class lista_registro(models.Model):
personal_id = models.ForeignKey(personal, on_delete=models.CASCADE)
dependencia_id = models.ForeignKey(dependencia, on_delete=models.CASCADE)
concepto_id = models.ForeignKey(concepto, on_delete=models.CASCADE)
fecha_realizado = models.DateField()
fecha_registro = models.DateField(auto_now_add=True)
descripcion = models.CharField(max_length=1000)
pago_id = models.ForeignKey(pago, on_delete=models.CASCADE, default=2)
monto = models.CharField(max_length=100)
def __str__(self):
return "===> " + self.descripcion + " <==="
well my problem is that I get a NOT NULL constraint error. I get that this is a date error but I don't know how to solve this
when you define a field that will not be required just set null=True, blank=True on your models file
fecha_realizado = models.DateField(null=True, blank=True)
class Team(models.Model):
team_name = models.CharField(max_length=50, null=False)
def __str__(self):
return self.team_name
class Tournament(models.Model):
types = (
('Round', 'Round'),
('Knockout', 'Knockout'),
)
teams = models.ManyToManyField(Team, related_name='tournament_teams')
tournament_name = models.CharField(max_length=50, null=False)
tournament_type = models.CharField(choices=types, max_length=40, null=False)
def __str__(self):
return self.tournament_name
class MatchRound(models.Model):
team_a_id = models.ForeignKey(Team, related_name="team_a")
team_b_id = models.ForeignKey(Team)
date = models.DateTimeField(null=True)
team_a_score = models.IntegerField(null=True)
team_b_score = models.IntegerField(null=True)
tournament_id = models.ForeignKey(Tournament, on_delete=models.CASCADE, null=True)
#receiver(post_save, sender=Tournament)
def create_match_round(sender, **kwargs):
type = kwargs.get('instance').tournament_type
if type == 'Round' and kwargs.get('created', False):
teams = kwargs.get('instance').teams.all()
schedule = create_schedule(teams)
for round in schedule:
for match in round:
team_a_id = match[0]
team_b_id = match[1]
tournament_id = kwargs.get('instance')
game = MatchRound.objects.create(team_a_id=team_a_id, team_b_id=team_b_id,
tournament_id=tournament_id)
I am trying to create a schedule for a tournament. So, I set up a trigger on MatchRound model and I am trying to get the teams of the tournament when it's created. However, the following line
teams = kwargs.get('instance').teams.all()
returns to an empty query set. I couldn't figure it out the problem.