Reputation: 47
I have 2 models employee and leave, where Employee
is the foreign key in Leave
. I want to display the leave requests by a specific employee on a page when they log in.
i'm not able to get the leave data populated on, and if there are more than 2 leaves applied by a single employee i get an error saying 2 items found
here is my code
models.py
class Employee(models.Model):
user=models.OneToOneField(User, on_delete=models.CASCADE)
no_of_leaves=models.IntegerField(
null=False,
validators=[
MinValueValidator(1),
MaxValueValidator(24)
],
default=24
)
def __str__(self):
return self.user.username
class Leave(models.Model):
employee=models.ForeignKey(Employee,on_delete=models.CASCADE,default="")
start_date=models.DateField(auto_now_add=False)
end_date=models.DateField(auto_now_add=False)
req_date=models.DateTimeField(default=datetime.datetime.now())
STATUS_OPTIONS = (
("Approve","Approve"),
("Pending","Pending"),
("Decline","Decline"),
)
approved=models.CharField(max_length=10,choices=STATUS_OPTIONS,default='Pending')
def __str__(self):
return self.employee.user.username
@property
def date_diff(self):
return (self.start_date - self.end_date).days
views.py
def home(request):
user = request.user
u = User.objects.get(username=user)
e = Employee.objects.get(user=user.id)
leave = Leave.objects.get_or_create(employee=e)
print(leave)
nofleaves=None
if user.is_superuser:
pass
else:
nofleaves=u.employee.no_of_leaves
context={'nofleaves':nofleaves,'leave':leave,}
return render(request,"leaveApp/home.html",context)
Upvotes: 0
Views: 806
Reputation: 128
Just like @Jao said get
is to fetch only one data while there is a many to one relationship between Leave
and Employee
that means there can be multiple Leave for one employee thus get
will throw an error.
You should use filter
:
Change this line
leave = Leave.objects.get_or_create(employee=e)
to something like
leave = Leave.objects.filter(employee=e.id)
if not leave.exists():
leave = Leave.objects.create(employee=e)
Upvotes: 3
Reputation: 586
This other question might help.
The thing is you should use get
for only one data. You shouldn't use get
on a many-to-one relathionship. The logic is, there can be multiple Leave
by Employee
so you can't have a consistent use of get
.
What you can use is filter but I'd use related names/related fields which will allow you to use employee.leaves
if you define it correctly.
Upvotes: 2