Django中的非主键外键 [英] Non-primary foreign keys in Django

查看:142
本文介绍了Django中的非主键外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从数据库的两个表,我想从Django站点访问。它们如下所示:

 表A 
id(int,primary key)
name(string,唯一)
...

表B
id(int,主键)
名称
record_date
(name,record_date是唯一的一起)
...

如何告诉我的Django模型表 A B 之间的一对多关系 A.name = B.name ?常规的 ForeignKey 关系将要求 B 使用 A.id 而不是名称,但是我不能修改现有的遗留数据库的结构。

解决方案

使用 to_field db_column 选项。

 
name = models.ForeignKeyField(A,to_field =name,db_column =name)
/ pre>

创建外键后,您可以访问值和相关实例,如下所示:

 >>> b = B.objects.get(id = 1)
>>> b.name_id#存储在name数据库列中的值
>>> b.name#相关A实例


I have two tables from a legacy database that I want to access from a Django site. They look like this:

Table A
id (int, primary key)
name (string, unique)
...

Table B
id (int, primary key)
name
record_date
(name, record_date are unique together)
...

How do I tell my Django model that Table A has a one-to-many relationship with B on A.name=B.name? The regular ForeignKey relationship would require that B use A.id instead of name, but I can't modify the structure of the existing legacy database.

解决方案

Use the to_field and db_column options.

class B(models.Model):
    name = models.ForeignKeyField(A, to_field="name", db_column="name")

Once you have created the foreign key, you can access the value and related instance as follows:

>>> b = B.objects.get(id=1)
>>> b.name_id # the value stored in the 'name' database column
>>> b.name # the related 'A' instance

这篇关于Django中的非主键外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆