6

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?

Tikitu
  • 679
  • 6
  • 22

2 Answers2

2

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

Ashok
  • 10,373
  • 3
  • 36
  • 23
  • I didn't expect it would... but it did: `unique_together` is all that is needed to stop Django asking for a primary key column. If you add that (or words to that effect) to your answer I can accept it. (Afaik `db_index` is irrelevant: it applies only to individual fields.) – Tikitu Jun 22 '10 at 10:14
  • While it is true that Django doesn't complain anymore if you add unique_together *but* it is still not fully functional. For example delete (Model.Delete()) on the model in specified in the through parameters will except. I'm expert enough to dare gives this as an answer, for what I read Django doesn't support no having a primary key on a Model. – Boaz Jul 22 '10 at 18:54
  • @Tikitu Thank you, thank you, thank you! I was tearing my hair out trying to figure a way to make Django not require a `primary_key=True` column for my legacy read-only database with several many-to-many intermediate tables. I knew about `unique_together`, but I didn't realize it would make Django's insistence upon `primary_key=True` go away. Now that Django 1.8 actually issues warnings about setting `primary_key=True` on a ForeignKey field, this suddenly became very important. – coredumperror Jul 31 '15 at 03:01
1

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.

Tikitu
  • 679
  • 6
  • 22
  • Not really, it will create `id` field as well. There's a [workaround](https://stackoverflow.com/a/28712960/52499). But actually in my case I decided to go with extra `id` field. No legacy tables. – x-yuri Feb 08 '18 at 21:35