Search code examples
pythondatabasedjangomodelsrelationships

Django Models ManyToMany and Foreign Key


Trying to get a better handle on how django database relationships are handled. Any thoughts are appreciated.

Considering the following example models:

class Things(models.Model):
    name = models.CharField(max_length=20)

class Stuff(models.Model):
    name = models.CharField(max_length=20)
    information = models.ManyToManyField('Information')
    things = models.ForeignKey('Things')

class Information(models.Model):
    name = models.CharField(max_length=20)
    stuff = models.ForeignKey('Stuff')

An error results from syncdb: AttributeError: 'ManyToManyField' object has no attribute 'ForeignKey'. The error results if I include both the ManyToManyField and the Foreign Key fields in the Stuff model.

Is there a way that I can make both of these relationships exist? Thanks for any ideas.


Solution

  • If you want to know how many information are linked to each stuff, django will provide a default manager that will allow you to go backwards; for this you don't need a foreign key in stuff.

    class Things(models.Model):
        name = models.CharField(max_length=20)
    
    class Stuff(models.Model):
        name = models.CharField(max_length=20)
        information = models.ManyToManyField('Information')
        things = models.ForeignKey('Things')
    
    class Information(models.Model):
        name = models.CharField(max_length=20)
    

    This model will allow you to do queries like:

    • "What is the information for stuff X ?"
    • "For stuff Y, what information is linked?"
    • "Find me all stuff and information for thing Z"

    In addition it will allow you have multiple information for each stuff and multiple stuff for each thing.

    Writing down these questions at the start will help you develop accurate models without unnecessary links/relations in your database.