If you had a custom table name, you would use that custom table name. This is the name of the table in the database, so it is "team", not the name of the model class Team (with a capital T). Inside it has the name of the table, then a dot, and then the name of the column. The value in this column team_id will be the same integer that is in some row in the id column on the team table. A " foreign key" just means that this column will have the key to identify a row in a foreign table. This tells the database that this column team_id is a foreign key to the table team. In Field() we pass the argument foreign_key="team.id". ![]() ![]() We add a default of None to the Field() so we don't have to explicitly pass team_id=None when creating a hero. It will be an integer, and it could be NULL in the database (or None in Python), because there could be some heroes that don't belong to any team. create_all ( engine ) def main (): create_db_and_tables () if _name_ = "_main_" : main () Import the things we need from sqlmodel and create a new Team model:įrom typing import Optional from sqlmodel import Field, SQLModel, create_engine class Team ( SQLModel, table = True ): id : Optional = Field ( default = None, primary_key = True ) name : str = Field ( index = True ) headquarters : str class Hero ( SQLModel, table = True ): id : Optional = Field ( default = None, primary_key = True ) name : str = Field ( index = True ) secret_name : str age : Optional = Field ( default = None, index = True ) team_id : Optional = Field ( default = None, foreign_key = "team.id" ) sqlite_file_name = "database.db" sqlite_url = f "sqlite:/// " engine = create_engine ( sqlite_url, echo = True ) def create_db_and_tables (): SQLModel. Let's start by creating the tables in code. Create Tables in Code ¶ Create the team Table ¶ But there's also many-to-many and one-to-one relationships. This is probably the most popular type of relationship, so we'll start with that. The many-to-one part can be seen if we start from the heroes, many heroes could be part of one team. So it is commonly called a one-to-many or many-to-one relationship. Here we are creating connected data in a relationship where one team could have many heroes. This way each row in the table hero can point to a row in the table team: To connect them, we will add another column to the hero table to point to each team by the ID with the team_id: id We have been working with heroes in a single table hero. So, the first step is to create more than one table and connect them, so that each row in one table can reference another row in the other table. Now we will deal with connected data put in different tables.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |