yamachan
yamachan

Reputation: 1079

I'd like to get some data from auth_user table on Django

I want to get some data from auth_user table, but I only can get username.

views.py

from myapp.models import User2

result1 = User2.objects.filter(email="[email protected]")
print(result1)  # [<User: JohnLennon>]
result2 = User2.objects.filter(pk=1)
print(result2)  # [<User: JohnLennon>]

models.py

from django.contrib.auth.models import AbstractUser

class User2(AbstractUser):

Using pdb, these don't work.

(Pdb)result1.id
(Pdb)result2.email
*** AttributeError: 'QuerySet' object has no attribute 'email'

I can get data from another tables. Like,

views.py

rows = User_Profile.objects.filter(uid=1)

test.html

{% for row in rows %}
    {{ row.fname }} 
{% endfor %}

But, I can't do same way from auth_user table. How can I get user's data from auth_user table like first_name and email?

Upvotes: 0

Views: 1188

Answers (2)

v1k45
v1k45

Reputation: 8250

When you do

result1 = User2.objects.filter(email="[email protected]")

A QuerySet List is created. result1 is not a QuerySet object, so you cannot access attributes of the user by printing attrs of list.

Either you have to user get() method like this

result1 = User2.objects.get(email="[email protected]")

Or directly access the first object of the QuerySet List, like this:

result1 = User2.objects.filter(email="[email protected]")[0]

Upvotes: 1

yamachan
yamachan

Reputation: 1079

Sorry. it seems I was confused...

(Pdb) for i in result: i.email
'[email protected]'

It worked.

Upvotes: 0

Related Questions