Skip to content

How to Initialise & Populate a Postgres Database with Circular ForeignKeys? #1481

Answered by eseglem
AyrtonB asked this question in Questions
Discussion options

You must be logged in to vote

The issue lies mostly with how the tables need to be defined in PG. Circular foreign keys in PG they need to be initially deferred, or else you run into the issue of them not being defined like you see.

Using Field(foreign_key="") is just a baseline sqlalchemy.ForeignKey under the hood with no extra args. I believe you need to go back to defining the Column to do that, based on what I see in the code.

The following worked for me with the original second half:

import uuid
from typing import Optional, List

from pydantic import UUID4
from sqlmodel import Session, Field, SQLModel, Relationship, create_engine
from sqlalchemy import Column, ForeignKey
from sqlalchemy.dialects.postgresql import U…

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by YuriiMotov
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
3 participants
Converted from issue

This discussion was converted from issue #313 on August 11, 2025 18:29.