[Answered ]-Access Users Model foreign Key

2👍

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

    • Use singular words for classes
    • Begin class name with capital letter
    • Begin class field with non capital letter
    • etc…
  • 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

0👍

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.

Leave a comment