0

我想检查行是否被删除,而不是为具有相同“名称”的其余行更新一个字段

添加新行时,我编写了一种方法来更新具有相同“名称”的所有行的字段,但无法为此提出解决方案

例如:

mysql> SELECT * FROM school_subjects;
  +----+-------------+---------+------------+---------------------+------------------+
    | id | name        | user_id | created_by | created_time        | num_of_followers |
    +----+-------------+---------+------------+---------------------+------------------+
    |  1 | Math 140    |       1 |            | 2012-08-06 20:21:38 |                5 |
    |  2 | Math 140    |       2 |            | 2012-08-06 20:22:15 |                5 |
    |  6 | Math 140    |       3 |            | 2012-08-07 20:05:48 |                5 |
    |  4 | Math 140    |       7 |            | 2012-08-07 18:58:14 |                5 |
    |  5 | lalala      |       7 |            | 2012-08-07 18:58:20 |                1 |
    |  7 | Math 140    |       8 |            | 2012-08-07 20:08:03 |                5 |
     ......................................

现在,如果我删除一行,我希望更改 num_of_followers 的结果:

+----+-------------+---------+------------+---------------------+------------------+
| id | name        | user_id | created_by | created_time        | num_of_followers |
+----+-------------+---------+------------+---------------------+------------------+
|  1 | Math 140    |       1 |            | 2012-08-06 20:21:38 |                4 |
 ------------------------------DELETED---------------------------------------------
|  6 | Math 140    |       3 |            | 2012-08-07 20:05:48 |                4 |
|  4 | Math 140    |       7 |            | 2012-08-07 18:58:14 |                4 |
|  5 | lalala      |       7 |            | 2012-08-07 18:58:20 |                1 |
|  7 | Math 140    |       8 |            | 2012-08-07 20:08:03 |                4 |
 ......................................

#models.py
class Subjects(models.Model):
    """ Subject Database """
    name = models.CharField(max_length=64, unique=False) #Subject Names on left-menu 
    user = models.ForeignKey(User, unique=False)
    created_by = models.CharField(max_length=64, unique=False)
    created_time = models.DateTimeField(editable=False)
  #  updated_time = models.ForeignKey()
    num_of_followers = models.IntegerField()
  #  num_of_documents = models.IntegerField()

    def __unicode__(self):
        return '%s %s' %(self.name, self.user.username)

    def update_followers(self):
        number = Subjects.objects.filter(name = self.name).count()+1
        Subjects.objects.filter(name= self.name).update(num_of_followers=number)
        return number

    def save(self, *args, **kwargs):
        self.num_of_followers = Subjects.update_followers(self)
        if not self.id:
            self.created_time = datetime.now()
        self.updated_time= datetime.now()
        super(Subjects, self).save(*args, **kwargs)
4

0 回答 0