Django 1:M Relationships
Django makes it easy to attach different types of data to your models that define what is saved in your database. It's easy to add integers, floats, dates, datetimes, short text, long text and lots of stuff.
Oh, here's a link to all of the fields Django provides for models, and links to their documentation on one-to-many and many-to-many relationships:
Of course, Django also has ways to hook up one-to-many and many-to-many relationships. Django establishes one-to-many relationships using a model.ForeignKey()
field.
You'll need to add a ForeignKey field to a model to set up the association, then, after that's added, create and run some migrations.
Here's an example that shows how to model Arists, Albums and Songs and hook them up to each other:
Now that these models are defined, have Python detect the changes and use manage.py
to create migrations and run them:
Now that relationships have been set up you can create models on the server and save models as fields of other models. Let's practice creating relations by firing up the Django shell. You'll need to import the models from your app to have access to them in the shell.
Run a query to grab all of the song objects and make sure they're saved and retrieved properly. Use a for loop to iterate through each of the songs and print out the songs title, the title of the album, and the name of the artist:
Customizing Admin Panel
User Associations
If you ever want to associate models to a specific user then you can import Django's built-in User model and reference it as a ForeignKey just like any other model.
Import Django's User
model from their auth model module, then use that model when you declare a ForeignKey field.
Last updated