Home > database >  How can i get username througth queryset?
How can i get username througth queryset?

Time:05-31

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.

CodePudding user response:

You can use the index to get the object.

print(Comments.objects.filter(pk=1)[0].username)

CodePudding user response:

You are getting the id because Django writes the relation as an ID of the object that is related to the other object. For instance, in the table Comment in your database, the column user keeps the ID of the row of the table User.

To actually get the username your can simply do Comments.objects.filter(pk=1).values('user__username')

  • Related