0

我有一个代表项目的 django 模型,每个项目都可以存储在一个特定的组中,如下所示:

+----+----------+-----+--------+
| id | group_id | ... | rel_id |
+----+----------+-----+--------+
|  1 |        1 | ... |      1 |
|  2 |        1 | ... |      2 |
|  3 |        2 | ... |      1 |
|  4 |        2 | ... |      2 |
|  5 |        1 | ... |      3 |
|  6 |        3 | ... |      1 |
|  7 |        1 | ... |      4 |
|  8 |        1 | ... |      5 |
+----+----------+-----+--------+

我需要以rel_id某种方式生成和存储该值。

所以基本上我想要和这里完全一样的东西:Relative incremental ID by reference field,但是动态计算不适合我,因为我必须操作表的内容(删除、更新、获取表的切片等) )。

做这个的最好方式是什么?

目前,我使用 PostgreSQL,但我想找到一个使用 django 抽象层的解决方案,因为我以后必须切换到 MySQL。

4

2 回答 2

0

这是您正在寻找的 - 一种创建 rel_id 列的方法吗?这应该在 PostgreSQL 中工作:

SELECT Id, 
  Group_Id, 
  Row_Number() OVER (PARTITION BY Group_ID ORDER BY Id) rn
FROM YourTable
ORDER BY Id

这是小提琴

这应该适用于 MySQL:

SELECT ID, Group_Id, RowNumber
FROM (
  SELECT Id, Group_ID,
    @row_num := IF(@prev_value=Group_Id,@row_num+1,1) AS RowNumber
     ,@prev_value := Group_Id as groupRowNumber
  FROM YourTable,
     (SELECT @row_num := 1) x,
     (SELECT @prev_value := '') y
  ORDER BY Group_ID
) t

还有小提琴

祝你好运。

于 2013-02-01T02:05:15.087 回答
0

 

class Item(models.Model): group = models.ForeignKey(Group) number = models.IntegerField() def save(self, force_insert=False, force_update=False, using=None): super(Item, self).save(force_insert = force_insert, force_update = force_update, using = using) self.number = Item.objects.filter(group = self.group).filter(id__lte = self.id).count() super(Item, self).save(force_insert = force_insert, force_update = force_update, using = using) </pre> </code>

That seems to work.
First save() fetches auto generated id, second save() updates record with rel_id, called number in this case.
Filtering with id_lte
用于消除竞争条件。

于 2013-02-01T12:14:16.430 回答