djangodjango-rest-frameworkdjoser

How can i get username througth queryset?


I have some model:

class Comments(models.Model):
user = models.ForeignKey(User, related_name='user_comment', on_delete=models.CASCADE)

heading = models.CharField(max_length=100)
score = models.IntegerField(default = 1, validators=[MinValueValidator(1), MaxValueValidator(5)])
text = models.CharField(max_length=1000)
created_at = models.DateTimeField(auto_now_add=True)

class Meta:
    ordering = ['-created_at',]

def __str__(self):
    return self.heading

And i when make .get request in shell:

Comments.objects.get(pk=1).user    

I get:

<User: user9>

But when i make that request:

 Comments.objects.filter(pk=1).values('user') 

I get:

<QuerySet [{'user': 9}]>

For some reason, in the queryset I get only id, but not username. Due to the peculiarities of my application, I need to use exactly .filter or .all (), so I must somehow get the username in the queryset. Please help me.


Solution

  • If you want to get all usernames from the QuerySet:

    usernames = Comments.objects.filter(pk=1).values_list('username', flat=True)
    

    If you want to get the first username from the QuerySet:

    comment_qs = Comments.objects.filter(pk=1).values_list('username', flat=True)
    username = comment_qs.first() if comment_qs.exists() else 'Unknown'
    

    or

    try:
        comment = Comments.objects.get(pk=1)
    except Comments.DoesNotExist:
        username = 'Unknown'
    else:
        username = comment.username