How to add multiple foreign key in Django

675 views Asked by At

I am beginner in Django. I am having two models

class Employee(models.Model):
    full_name = models.CharField(max_length=120,default=None)
    designation = models.CharField(max_length=80,default=None)

class Leave(models.Model):
    employee = models.ForeignKey(Employee, related_name='employee')
    number_of_days = models.IntegerField(default=0)

Now I have inline Leave Model with Employee in admin.py so that I can add as many leaves I want in employees But when I retrieve this model in views new Leaves are created, all I want is one employee should show total = number of days, but it creates new leaves, not able to build any logic here I am stuck, please ask if u don't understand what I am asking.

1

There are 1 answers

1
user2390182 On

Not exactly sure what you are asking, but my guess is you want to display the total number of absent days of an employee in the admin. You can use aggregation and Sum in particular and a custom method on your model:

# models
from django.db.models import Sum

class Employee(models.Model):
    def absent_days(self):
        return self.leaves.aggregate(s=Sum('number_of_days'))['s'] or 0
    absent_days.short_description = 'Absent days'  # used as column header/field label

class Leave(models.Model):
    # note the changed related name!
    employee = models.ForeignKey(Employee, related_name='leaves')

# admin
class EmployeeAdmin(admin.ModelAdmin):
    readonly_fields = [..., 'absent_days', ...]
    fields = [..., 'absent_days', ...]
    list_display = [..., 'absent_days', ...]