行が削除されたかどうかを確認し、残りの行の 1 つのフィールドを同じ「名前」で更新したい
新しい行が追加されたときに同じ「名前」を持つすべての行のフィールドを更新する方法を書きましたが、これに対する解決策を思い付くことができません
例えば:
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 |
......................................
そして今、1 行を削除すると、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)