通过模型为ManyToMany分配索引

时间:2016-03-26 17:27:38

标签: django

是否可以在ManyToMany关系中为对象分配索引?如果我有这些模型:

class Group(models.Model):
    items = models.ManyToManyField(GroupItem, unique=False, through=GroupItem)

class GroupItem(models.Model):
    group = models.ForeignKey(Group, unique=False)
    index = models.IntegerField()

当我创建一个组项时,我希望能够按索引对该项进行排序。所以,如果我有一个小组:

MyGroup = [MyItem1, MyItem2, MyItem3]

但我希望MyItem3成为第一个这样的项目:

MyGroup = [MyItem3, MyItem1, MyItem2]

我该怎么做?如果我可以让索引自动增加,因为更多对象被添加到Group

1 个答案:

答案 0 :(得分:1)

您可以通过使用适当的默认可调用来实现此目的:

class Group(models.Model):
    items = models.ManyToManyField(Track, through="GroupItem")

class Track(models.Model):
    pass

class GroupItem(models.Model):
    group = models.ForeignKey(Group)
    track = models.ForeignKey(Track)
    index = models.PositiveSmallIntegerField(default=get_index)

def get_index():
    latest = GroupItem.objects.aggregate(models.Max("index"))
    latest_index = latest["index__max"]

    # using 0-based indexing, for example
    return latest_index + 1 if latest_index is not None else 0
相关问题