python - Non-primary foreign keys in Django -
i have 2 tables legacy database want access django site. this:
table id (int, primary key) name (string, unique) ... table b id (int, primary key) name record_date (name, record_date unique together) ...
how tell django model table a
has one-to-many relationship b
on a.name=b.name
? regular foreignkey
relationship require b
use a.id
instead of name
, can't modify structure of existing legacy database.
use to_field
, db_column
options.
class b(models.model): name = models.foreignkeyfield(a, to_field="name", db_column="name")
once have created foreign key, can access value , related instance follows:
>>> b = b.objects.get(id=1) >>> b.name_id # value stored in 'name' database column >>> b.name # related 'a' instance
Comments
Post a Comment