Reputation: 11
I am writing my first Django App where I am wanting to utilise the built in user model to map to my own custom model.
My application is going to manage Users IT devices. To do this, I have a table called devices. I am wanting a foreign key per device that maps to the user model (so one user can have multiple devices).
My question is, how do I add that mapping in my model. Some thing?
Class Devices(model.Model):
DeviceID = model.CharField(MaxLength=10)
Owner = model.ForeignKey(<User??>)
Thanks in advance,
Paul
Upvotes: 1
Views: 45
Reputation: 149
To access Django's in-built User
model, you need to import this:
from django.contrib.auth.models import User
Assuming you have imported models:
from django.db import models
NOTE: it's models
instead of model
. This typo also exists in Liarez's answer.
Upvotes: 0
Reputation: 10563
class Device(model.Model):
deviceID = model.CharField(MaxLength=10)
owner = model.ForeignKey(User)
You should check the standarts for coding styles Django Coding Style Standarization
You should also check oficial documentation Django: Foreign Key
After a model is related to another via ForeignKey
you can do following actions, If you have a Device object in a variable called dev
:
dev.owner # This return an User object, so you can access all user fields
dev.owner.username
dev.owner.email
Upvotes: 2