1

When I am using this queryset I am not getting any error and it's returning the user id

UserProfile.objects.get(forget_password_token=forget_password_token)
print(user.user_id)

>>>19

But when I am using this queryset UserProfile.objects.filter(forget_password_token=forget_password_token) why I am getting this error QuerySet' object has no attribute 'user_id'

what is difference between get and filter in Django ? why not working filter method here?

When user putting wrong code in input fields then it's rising this error UserProfile matching query does not exist.

boyenec
  • 1,405
  • 5
  • 29
  • Also see [Difference between Django's filter() and get() methods](https://stackoverflow.com/questions/3221938/difference-between-djangos-filter-and-get-methods) – Abdul Aziz Barkat Oct 07 '21 at 05:42
  • 1
    ```get()``` will return you a single object where you can access all the attributes of your object but ```filter()``` will return queryset to access your object from queryset you need to iterate it oe you can use ```.first()``` method to get first object like this ```UserProfile.objects.filter(forget_password_token=forget_password_token).first()``` and than you can access ```user.user_id``` – Ankit Tiwari Oct 07 '21 at 05:42
  • @Abdul Aziz Barkat I read the question but I didn't understood properly about concept of get and filter so I post question here. – boyenec Oct 07 '21 at 05:42
  • @Ankit Tiwari Thanks for the clarification – boyenec Oct 07 '21 at 05:43

1 Answers1

3

With .get() the return the instance of the object found so you can check directly user_id. With .filter() the rturn is a query set object contain all instances of ogject found (you can compare it to a list of results with some différences as it's an object type Queryset) So if you Want to check user_id, you have first to iterate all élément of the queryset

test = UserProfile.objects.filter(forget_password_token=forget_password_token)
for result in test:
    print(test.user_id)

Another way can be to return the result in a list with .values_list()

test = UserProfile.objects.filter(forget_password_token=forget_password_token).values_list('user_id')
Renaud
  • 2,709
  • 2
  • 9
  • 24