python - How to add multiple foreign key in Django -


i beginner in django. having 2 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 have inline leave model employee in admin.py can add many leaves want in employees when retrieve model in views new leaves created, want 1 employee should show total = number of days, creates new leaves, not able build logic here stuck, please ask if u don't understand asking.

not sure asking, guess want display total number of absent days of employee in admin. can use aggregation , sum in particular , custom method on model:

# models 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 column header/field label  class leave(models.model):     # note 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', ...] 

Comments

Popular posts from this blog

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -

python - Error while using APScheduler: 'NoneType' object has no attribute 'now' -