0

I have a model called Employee:

Employee:

  • Name: CharField
  • Email: EmailField
  • Age: IntegerField
  • Ranking: IntegerField

My problem comes with the Ranking field. The Ranking field is supposed to determine an order for the employees, which I determine based on how much work they do. I set this value in Django admin.

The problem is that if I add an employee and I put them at Ranking = 2, I have to adjust every single other employee's Ranking after 2. Does this make sense. How can I avoid this?

Thanks!

5
  • 1
    You could try linked list approach. Replace your Ranking field with EmployeeAbove field which will be a foreign key pointing to the employee that comes before in the ranking order. This way you need to update maximum 3 employees no matter how many total employees you have in your table.
    – user10456940
    Jul 22, 2020 at 1:26
  • Why not use a FloatField? If you need to insert in between two values, you use the average between the two. So between 2 and 3, you can use 2.5. Between 2 and 2.5 you can use 2.25, etc. Jul 22, 2020 at 1:30
  • @WillemVanOnsem I am hesitant to use floats as it seems a bit clunky, but will consider.
    – user11141180
    Jul 22, 2020 at 1:37
  • @ShahinMursalov this sounds like an interesting idea. How could i set it up so that two people can't point to one person though?
    – user11141180
    Jul 22, 2020 at 1:37
  • @ShahinMursalov You should post this as an answer, although it makes it harder to determine, say, who the 100th employee is.
    – Selcuk
    Jul 22, 2020 at 1:46

1 Answer 1

0

Ok, this hasn't been tested but the general idea is to override the .save() method so that you can recalculate the rankings for other instances when the ranking of an instance change:

class Employee(models.Model):
    ...
    def save(self, *args, **kwargs):
        other_employees = Employee.object.exclude(pk=self.pk).order_by("ranking")
        i = 1
        for employee in other_employees:
            if i == self.ranking:
                i += 1
            employee.ranking = i
            employee.save()
        super(Employee, self).save(*args, **kwargs)

Note that this is not production quality code. You should probably do something about race conditions (such as when two people save two Employee objects at the same time) and other quirks.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.