0
models.py
class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    profile_img = models.ImageField(upload_to='ProfileImg', default='ProfileImg/default-avatar.png')
    feedback = models.CharField(max_length=100, null = True)

views.py

While using objects.get()

        user = User.objects.get(id=request.user.id)
        user.userprofile.feedback = sentiment_Value 
        user.save()

it is working fine.

but while using objects.filter()

 user = User.objects.filter(id=request.user.id)
 user.userprofile.feedback = sentiment_Value 
 user.save()

I'm getting error

user.userprofile.feedback = sentiment_Value
AttributeError: 'QuerySet' object has no attribute 'userprofile'

and the user returns

user: <QuerySet [<User: snegi8005>]>

I don't know why this is happening. I thought both get() and filter() function work same the only difference is get() raises exception if nothing found and filter() return none if no match found.

how get() and filter() works?

Please correct me if i'm wrong and help me solving this.

i want to get the user's data of a user.id and the associated table userprofile data also. in case data not found it should return none or should not raise exception. I know i can use get() with try/except block but that would be too much of code for me.

sandeepnegi
  • 123
  • 13
  • `get` gets a single item (and raises an exception if there are not exactly one). `filter` makes a subsetted queryset (actual evaluation is deferred) – alani Aug 28 '20 at 07:25
  • `User.objects.filter(....).first()` might do what you want. If the queryset is empty, then `first()` will return `None` rather than raise an exception. – alani Aug 28 '20 at 07:33
  • I would have posted it as an answer in order to give you more detail, but this question was closed on the grounds of a so-called "duplicate" which did not in fact answer your question of how to get the object or `None` without using "too much code" (such as writing a try/except block). – alani Aug 28 '20 at 07:36
  • @alani I figure it out just now . thanx for that. but one more thing to ask. if my queryset contains only one row data then why i need to use .first(). – sandeepnegi Aug 28 '20 at 07:39
  • Because the result of `filter` is still a QuerySet, not an individual object **even if there is only one**. And in fact, it is probably not even evaluated at that point (so the number of results is unknown until it is needed) - the actual search of the database happens when you try to extract objects from it e.g. by calling `first()` – alani Aug 28 '20 at 07:40

0 Answers0