1

The problem is that, I related (Legacy) table to (UserProfile) django models with M2MField and also through an intermediary table, but there seems to be no relation generated. Legacy table is just one table with no other relations.

I am using Anaconda distribution with Python version 2.7, django 1.8, and PostgreSQL 9.4. Here are codes.

models.py

from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User

class Legacy(models.Model): # Legacy DB with no pk column
    ... # columns
    class Meta:
        managed = False
        db_table = 'legacydb_name'

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    username = models.CharField(max_length = 16)

    mylegacy = models.ManyToManyField(Legacy,
                                      through = 'Legacylink',
                                      related_name = 'legacy_mylegacy')
    def __unicode__(self):
        return "%s"%(self.user, )

class Legacylink(models.Model):
    userprofile = models.ForeignKey(UserProfile)
    yourlegacy = models.ForeignKey(Legacy)

    class Meta:
        db_table = 'legacy_link'
        unique_together = ('userprofile','yourlegacy')

admin.py

from django.contrib import admin
from myapp.models import UserProfile, Legacy, Legacylink

# Register your models here.
admin.site.register(UserProfile)
admin.site.register(Legacy)
admin.site.register(Legacylink)

After migration with no error, the genereated UserProfile table shows no relation between UserProfile and Legacy DB. I mean, the UserProfile table has no column named my legacy and there is no table named Legacylink.

I've googled a lot about how to use ManyToManyField with a legacy database... Also I am really thankful to SO for giving many helps like unique_together, about ProgrammingError, intermediary table. I followed many guides there but I couldn't solve my problem...

Here's what I ask:

  1. Must the Legacy DB have an id column for primary_key?
  2. How do I check whether M2M relation is successfully created?

Also I would be grateful if you let me know some guidelines for treating the legacy DB with M2MField.

Community
  • 1
  • 1
Leonard2
  • 894
  • 8
  • 21
  • 1
    I'm not quite sure what you are expecting here. Many-to-many relations don't exist as physical fields; the legacy_link table will contain all the relationship data. – Daniel Roseman Sep 03 '15 at 08:16
  • @daniel It seems so. When I try m2m field on the simplest example without legacy DB, it works well... also additionally using intermediary table, django does not automatically generate the intermediary table, the same as the case using the legacy DB. I am quite new to django and also web programming, so guess I need to study more. Thank you for the comment. – Leonard2 Sep 04 '15 at 00:52

0 Answers0