The foreign key associated with column 'x.y' could not … generate a foreign key to target column 'None'

后端 未结 1 826
一生所求
一生所求 2021-01-21 04:35

I am during creating my first database project in SQLAlchemy and SQLite. I want to connect two entity as relational database\'s relational model. Here is the source:

<         


        
1条回答
  •  时光说笑
    2021-01-21 05:31

    From the docs:

    The argument to ForeignKey is most commonly a string of the form ., or for a table in a remote schema or “owner” of the form ... It may also be an actual Column object...

    In defining your ForeignKey on Cars.id_model you pass the string form of a class name ('Models') which is not an accepted form.

    However, you can successfully define your foreign key using one of the below options:

    ForeignKey(Models.id_model)
    

    This uses the actual Column object to specify the foreign key. The disadvantage of this method is that you need to have the column in your namespace adding extra complexity in needing to import the model into a module if it is not defined there, and also may cause you to care about the order of instantiation of your models. This is why it's more common to use one of the string-based options, such as:

    ForeignKey('models.id_model')
    

    Notice that this example doesn't include the string version of the class name (not Models.id_model) but rather the string version of the table name. The string version means that table objects required are only resolved when needed and as such avoid the complexities of dealing with Column objects themselves.

    Another interesting example that works in this case:

    ForeignKey('models')
    

    If the two columns are named the same on both tables, SQLAlchemy seems to infer the column from the table. If you alter the name of either of the id_model columns definitions in your example so that they are named differently, this will cease to work. Also I haven't found this to be well documented and it is less explicit, so not sure if really worth using and am really just mentioning for completeness and because I found it interesting. A comment in the source code of ForeignKey._column_tokens() seemed to be more explicit than the docs with respect to acceptable formatting of the column arg:

        # A FK between column 'bar' and table 'foo' can be
        # specified as 'foo', 'foo.bar', 'dbo.foo.bar',
        # 'otherdb.dbo.foo.bar'. Once we have the column name and
        # the table name, treat everything else as the schema
        # name.
    

    0 讨论(0)
提交回复
热议问题