2015-09-06 51 views
0

我已经在Django以下型号:如何从SqlAlchemy中的Django ORM描述一对一关系?

class News(models.Model): 
    title = models.CharField(max_length=1000) 
    # some fields 
    image = models.ForeignKey("media.Image",blank=True, null=True) 

# and in another django module 
class Image(models.Model): 
    url = models.URLField(max_length=1000) 

在Postgres里它看起来像:

=> \d newsfeed_news 

    Column |   Type   |       Modifiers       
-------------+--------------------------+------------------------------------------------------------ 
id   | integer     | not null default nextval('newsfeed_news_id_seq'::regclass) 

... 

image_id | integer     | 

这意味着字段“图像”中的表 - 仅仅是整数字段,包含的ID图片。

我试图建立在SQLAlchemy的这些关系:

class Image(Base): 
    __tablename__ = 'media_image' 
    id = Column(Integer, primary_key=True) 
    url = Column('url',String) 

class newsTable(Base): 
    __tablename__ = 'media_news' 
    id = Column(Integer, primary_key=True) 
    # some fields 
    image_id = Column(Integer, ForeignKey('Image.id')) 
    image = relationship("Image", uselist=False) 

但我得到了以下错误:

Can't find any foreign key relationships between 'newsfeed_news' and 'media_image'. Could not determine join condition between parent/child tables on relationship newsTable.image - there are no foreign keys linking these tables.

Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression.

我做了什么错?

回答

0

根据文档ForeignKey接受column参数,其定义为:

A single target column for the key relationship. A Column object or a column name as a string: tablename.columnkey or schema.tablename.columnkey .

试图指定列名作为字符串,但没有名为Image表。您可以从Image模型直接引用Column对象:

image_id = Column(Integer, ForeignKey(Image.id)) 

,或者提供一个正确的表名:

image_id = Column(Integer, ForeignKey('media_image.id'))