Django:多对多通过一个表(只有)复合键 [英] Django: Many-to-many through a table with (only) compound key

查看:111
本文介绍了Django:多对多通过一个表(只有)复合键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个遗留数据库,表中存有多对多关系,但没有单个主键列。有没有办法说服Django使用它?



原理图:

 产品1< ----> *标签*< ----> 1标签

标签表使用(product_id,label_id)作为复合主键,我不看到任何方式通知Django这个。 (只是使用通过给我'列表'中的未知列'labels.id'。)



我需要回到自定义SQL吗?或者我错过了某些东西?

解决方案

如果您将 unique_together 添加到对于多对多表的模型,Django将使用这些列,而不是期望一个名为 id 的主键。


I have a legacy database with a table storing a many-to-many relationship, but without a single primary key column. Is there any way to convince Django to use it anyway?

Schematically:

Product 1<---->* Labeling *<---->1 Label

The Labeling table uses (product_id,label_id) as a compound primary key, and I don't see any way to inform Django about this. (Just using through gives me Unknown column 'labeling.id' in 'field list'.)

Do I need to fall back to custom SQL? Or am I missing something?

解决方案

If you add a unique_together to the model for the many-to-many table, Django will use those columns instead of expecting a primary key called id.

这篇关于Django:多对多通过一个表(只有)复合键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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