@@ -504,3 +504,61 @@ def test_alter_type_binary_to_char(self):
504
504
'''ALTER TABLE test_pony DROP COLUMN "hash" CASCADE;''' ,
505
505
'''ALTER TABLE test_pony RENAME COLUMN "hash_tmp" TO "hash";''' ,
506
506
], sqls )
507
+
508
+ @postgres_fixture ()
509
+ def test_foreign_key_to_id (self ):
510
+ new_state = self .set_up_test_model ('test' )
511
+ operations = [
512
+ migrations .CreateModel (
513
+ 'Rider' ,
514
+ [
515
+ ('id' , models .AutoField (primary_key = True )),
516
+ ('pony' , models .ForeignKey ('Pony' , models .CASCADE )),
517
+ ],
518
+ ),
519
+ ]
520
+ with self .collect_sql () as sqls :
521
+ self .apply_operations ('test' , new_state , operations )
522
+
523
+ if TEST_WITH_POSTGRES :
524
+ identity = "serial"
525
+ elif TEST_WITH_REDSHIFT :
526
+ identity = "integer identity(1, 1)"
527
+
528
+ self .assertEqual ([
529
+ f'''CREATE TABLE "test_rider" ("id" { identity } NOT NULL PRIMARY KEY, "pony_id" integer NOT NULL) ;''' ,
530
+ '''ALTER TABLE "test_rider" ADD CONSTRAINT "test_rider_pony_id_3c028c84_fk_test_pony_id"'''
531
+ ''' FOREIGN KEY ("pony_id") REFERENCES "test_pony" ("id");''' ,
532
+ ], sqls )
533
+
534
+ @postgres_fixture ()
535
+ def test_foreign_key_to_non_id (self ):
536
+ new_state = self .set_up_test_model ('test' )
537
+ operations = [
538
+ migrations .AddField (
539
+ model_name = 'Pony' ,
540
+ name = 'remote' ,
541
+ field = models .IntegerField (unique = True , null = True ),
542
+ ),
543
+ migrations .CreateModel (
544
+ 'Rider' ,
545
+ [
546
+ ('id' , models .AutoField (primary_key = True )),
547
+ ('pony_remote' , models .ForeignKey ('Pony' , on_delete = models .CASCADE , to_field = "remote" )),
548
+ ],
549
+ ),
550
+ ]
551
+ with self .collect_sql () as sqls :
552
+ self .apply_operations ('test' , new_state , operations )
553
+
554
+ if TEST_WITH_POSTGRES :
555
+ identity = "serial"
556
+ elif TEST_WITH_REDSHIFT :
557
+ identity = "integer identity(1, 1)"
558
+
559
+ self .assertEqual ([
560
+ '''ALTER TABLE "test_pony" ADD COLUMN "remote" integer NULL;''' ,
561
+ f'''CREATE TABLE "test_rider" ("id" { identity } NOT NULL PRIMARY KEY, "pony_remote_id" integer NOT NULL) ;''' ,
562
+ '''ALTER TABLE "test_pony" ADD CONSTRAINT "test_pony_remote_e347b432_uniq" UNIQUE ("remote");''' ,
563
+ '''ALTER TABLE "test_rider" ADD CONSTRAINT "test_rider_pony_remote_id_269d66d9_fk_test_pony_remote" FOREIGN KEY ("pony_remote_id") REFERENCES "test_pony" ("remote");'''
564
+ ], sqls )
0 commit comments