Search code examples
djangodjango-modelsmany-to-manydjango-orm

Map Mannually Created Table as M2M in Django


I have table T1 (list of all words Used in Text) and T2 (list of Text).

I have created another Table T3 with foreign key to T1, and T2 so that it can act as M2M, in T3. I additionally add another column called WordCount, so i cannot create this table with models.ManyToMany Field! Can I access T2 from T1 using Many to many Constrains in Django ORM?


Solution

  • I think you need the "through" attribute in your many to many model:

    Here's a simple example I got from this link:

    https://gist.github.com/jacobian/827937

    You can find more about it here:

    https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.db.models.ManyToManyField.through

    In this case the example has a person with a many to many rel to groups. But we need some additional fields on the relation, so we create a Through Model called Group Member. Notice that the intemediate model GroupMember has a foreign key to both Person and Group, and some other fields that you might need.

    Django's ORM takes care of the constraints when you write the models like this.

    from django.db import models
    
    
    class Person(models.Model):
        name = models.CharField(max_length=200)
        groups = models.ManyToManyField('Group', through='GroupMember', related_name='people')
    
        class Meta:
            ordering = ['name']
    
        def __unicode__(self):
            return self.name
    
    class Group(models.Model):
        name = models.CharField(max_length=200)
    
        class Meta:
            ordering = ['name']
    
        def __unicode__(self):
            return self.name
    
    class GroupMember(models.Model):
        person = models.ForeignKey(Person, related_name='membership')
        group = models.ForeignKey(Group, related_name='membership')
        type = models.CharField(max_length=100)
    
        def __unicode__(self):
            return "%s is in group %s (as %s)" % (self.person, self.group, self.type)