[Answer]-How to get exactly models field after I filtered the models object?

1👍

✅

If you are querying a unique entry, use .get

tweets = Tweet.objects.get(username__iexact=username)

instead of .filter.
The filter() method will return an array, even if it is only one result.

And also, your query is wrong… You have username on your model, not user

(username__iexact=username)

https://docs.djangoproject.com/en/dev/topics/db/queries/

0👍

You need to filter your Tweets as such:

tweets = Tweet.objects.filter(username__iexact=username)

If you only want one Tweet back:

tweet = Tweet.objects.get(username__iexact=username)

Which tweet instance is returned would depend on the default ordering of the model, which is id unless you specify it in the model’s Meta options.

In the template, you need to either loop over the tweets returned to display tweet.username which only exists on an instance, or you need to pass in the username and just display:

<h1>{{ username }}</h1>

0👍

The Tweet model described above does not have any field user so the filter user__iexact will not work.

Assuming username is not unique as the model does not describe the username field to be unique

This can be changed as:
tweets = Tweet.objects.filter(username__iexact=username)

The filter queries always returns a list of objects.
TO access the first object use tweets[0]

to show the username we can use tweets[0].username

Leave a comment