Search code examples
djangomany-to-many

Must the classes in Django's many-to-many relationship be in the same models.py file?


Please help me better understand how the ManytoManyField works in Django. Maybe the examples I've seen are simple ones for beginners, but it seems in all the examples, the classes involved in ManytoManyFields are in the same models.py file. In my exercise (following a tutorial, I put the two classes in two different models.py file(different apps), and am struggling to make them connect. So my question #1: Do the classes in Django's many-to-many relationship have to be in the same models.py file? #2 For a true many-to-many relationship, do I need to create a "through" table/relationship?

Here is the relevant code snippets from the tutorial:

#app='household'
class Member(models.Model):    
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    # household = models.ForeignKey(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=100)
    photo = models.ImageField(
        upload_to='uploads/members/', default='/icons/member.svg')    
        
    def __str__(self):
        return '%s Household | %s' % (self.user, self.name)

#app=meals
class Meal(models.Model):    
    name = models.CharField(max_length=255)    
    date = models.DateField()    
    members = models.ManyToManyField('Member')

Solution

  • #1: Do the classes in Django's many-to-many relationship have to be in the same models.py file?

    No. If for example the other model is Foo in app2, you can write this as:

    class Meal(models.Model):
        foos = models.ManyToManyField('app2.Foo')

    #2 For a true many-to-many relationship, do I need to create a "through" table/relationship?

    No. Django will create a hidden model for the ManyToManyField if you do not specify a through=… yourself. That model will have two ForeignKeys: one to the "source" model, and one to the "target" model.

    If you want to add extra data in the many-to-many relation, you defines a custom through=… model to add extra data besided the two ForeignKeys.