差异Django模型的唯一自动生成的ID

时间:2019-01-09 14:19:07

标签: django inheritance django-models

我有3个从父抽象类继承的模型类,如下所示:

      class ParentClass(models.Model):
          class Meta:
              abstract = True

      class ChildClass1(ParentClass):
          ...


      class ChildClass2(ParentClass):
          ...


      class ChildClass3(ParentClass):
          ... 

我想知道是否有一种方法可以让Django像往常一样生成id,但是要确保ChildClass1ChildClass2ChildClass3的实例中都没有重叠的id。因此,例如以下代码:

    a = ChildClass1.objects.create()
    b = ChildClass2.objects.create()
    c = ChildClass3.objects.create()
    print(a.pk)
    print(b.pk)
    print(c.pk)

应返回:

    1
    2
    3

2 个答案:

答案 0 :(得分:1)

一个ID等于数据库中当前对象的数目。像这样:

class ParentClass(models.Model):
  class Meta:
    abstract = True

  @classmethod
  def get_next_id(cls):
    n_children = ChildClass1.objects.count() + ChildClass2.objects.count() + ChildClass3.objects.count()
    return n_children + 1

class ChildClass1(ParentClass):
  my_id = models.PositiveIntegerField(default=ParentClass.get_next_id, primary_key=True)
   ...

您可能希望使get_next_id更加聪明,以便像https://stackoverflow.com/a/49295674/1060339一样自动检查所有子类

答案 1 :(得分:0)

您可以获得不同型号的唯一主键

import uuid    
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)