Django: Many-to-many through a table with (only) compound key

一笑奈何 提交于 2019-12-23 09:31:23

问题


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?


回答1:


hope this helps you,

http://docs.djangoproject.com/en/dev/ref/models/options/#unique-together

http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.Field.db_index




回答2:


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.



来源:https://stackoverflow.com/questions/3091665/django-many-to-many-through-a-table-with-only-compound-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!