There is no data about the Student
and Teacher
models saved in the User
table, so you'll have to query for the related object.
If you don't need the actual profile (Student
or Teacher
object), the fastest way is to use the exists()
function on the related set:
if request.user.student_set.exists():
# student
elif request.user.teacher_set.exists():
# teacher
If you know you're going to need the profile object later on, it would be faster to fetch the results and check for an existing object in Python:
if request.user.student_set.all():
# do something with student_set
elif request.user.teacher_set.all():
# do something with teacher_set
Side note:
If your user shouldn't ever have more than one Student
or Teacher
object related, it might be a better idea to use a OneToOneField
instead of a ForeignKey
. That way, you don't have to bother with all()
etc, but you can just access the related model instance with user.student
or user.teacher
. This will also allow you to use select_related
, so that both the user object and the student or teacher object are fetched in a single query.