django同一张表ForeignKey

class TestModel(models.Model):
    name = models.CharField(max_length=100)
    title = models.CharField(max_length=200)
    test = models.ForeignKey('TestModel', on_delete=models.CASCADE, default=-1)

  #关联自身,表内一对多
  test = models.TestModel.objects.create(name='物理机', title='测试')
    models.TestModel.objects.create(name='虚拟机1', title='验证', test=test)
    models.TestModel.objects.create(name='虚拟机2', title='验证', test=test)
    models.TestModel.objects.create(name='虚拟机3', title='验证', test=test)

    test = models.TestModel.objects.get(id=3).test.name
    test = models.TestModel.objects.get(id=1).testmodel_set.all()
    for te in test:
        print(te.name, te.title)

  

你可能感兴趣的:(django同一张表ForeignKey)